What is 401 Status Code: Meaning and Usage in REST APIs
401 status code means "Unauthorized" in HTTP responses. It tells the client that they must provide valid authentication credentials to access the requested resource.How It Works
Imagine you want to enter a private club. The club's bouncer asks for your ID before letting you in. In web terms, the 401 Unauthorized status code is like that bouncer telling you, "You need to prove who you are before you can enter."
When a client (like a web browser or app) tries to access a protected resource on a server without proper login details, the server responds with 401. This means the server expects the client to send valid credentials, such as a username and password or a token, to prove their identity.
Unlike a 403 Forbidden status, which means "You are not allowed even if you try," 401 means "You haven't tried or your credentials are missing or wrong." The client can try again with the right credentials.
Example
This example shows a simple REST API endpoint in Python using Flask that requires a token for access. If the token is missing or wrong, it returns a 401 status code.
from flask import Flask, request, jsonify app = Flask(__name__) VALID_TOKEN = "secret123" @app.route('/protected') def protected(): token = request.headers.get('Authorization') if token != f"Bearer {VALID_TOKEN}": return jsonify({"error": "Unauthorized"}), 401 return jsonify({"message": "Welcome to the protected resource!"}) if __name__ == '__main__': app.run(debug=True)
When to Use
Use the 401 Unauthorized status code when a client tries to access a resource that requires authentication but has not provided valid credentials. This tells the client to authenticate first.
Common real-world cases include:
- Accessing user profile data on a website without logging in.
- Calling an API endpoint that requires an API key or token, but the key is missing or invalid.
- Trying to use a service after your login session has expired.
It helps keep resources secure by ensuring only authorized users can access sensitive information.
Key Points
- 401 means authentication is required or failed.
- It differs from 403, which means access is forbidden even with authentication.
- Clients should respond by asking users to log in or provide credentials.
- Commonly used in APIs and websites to protect private data.