How to Implement API Key Authentication in REST APIs
To implement
API key authentication, require clients to send a unique API key with each request, usually in the Authorization header or as a query parameter. The server checks this key against a stored list to allow or deny access.Syntax
API key authentication typically involves the client sending the key in the Authorization header or as a query parameter. The server then validates this key before processing the request.
Authorization: ApiKey YOUR_API_KEY- Common header format.?api_key=YOUR_API_KEY- Alternative query parameter.
http
GET /resource HTTP/1.1
Host: api.example.com
Authorization: ApiKey YOUR_API_KEYExample
This example shows a simple REST API server in Python using Flask that checks for an API key in the Authorization header and returns data only if the key is valid.
python
from flask import Flask, request, jsonify app = Flask(__name__) # A simple store of valid API keys VALID_API_KEYS = {"12345", "abcdef"} @app.route('/data') def data(): auth_header = request.headers.get('Authorization') if not auth_header or not auth_header.startswith('ApiKey '): return jsonify({"error": "Missing or invalid Authorization header"}), 401 api_key = auth_header.split(' ')[1] if api_key not in VALID_API_KEYS: return jsonify({"error": "Invalid API key"}), 403 return jsonify({"message": "Access granted", "data": [1, 2, 3]}) if __name__ == '__main__': app.run(debug=True)
Output
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Common Pitfalls
Common mistakes when implementing API key authentication include:
- Not using HTTPS, which exposes the API key to attackers.
- Sending the API key in URL query parameters, which can be logged or cached insecurely.
- Not validating the API key properly or allowing empty keys.
- Hardcoding API keys in client-side code, making them easy to steal.
Always keep API keys secret and use secure transport.
http
Wrong way: GET /data?api_key=12345 HTTP/1.1 Host: api.example.com Right way: GET /data HTTP/1.1 Host: api.example.com Authorization: ApiKey 12345
Quick Reference
Summary tips for API key authentication:
- Send API keys in the
Authorizationheader, not URL parameters. - Use HTTPS to protect keys in transit.
- Validate keys on every request.
- Rotate and revoke keys regularly.
- Limit permissions and usage per key.
Key Takeaways
Always require clients to send a unique API key with each request for authentication.
Validate the API key on the server before granting access to resources.
Use the Authorization header to send API keys securely over HTTPS.
Avoid sending API keys in URLs to prevent accidental exposure.
Regularly rotate and manage API keys to maintain security.