0
0
Flaskframework~5 mins

API key authentication concept in Flask

Choose your learning style9 modes available
Introduction

API key authentication helps protect your app by checking if users have a secret key before they can use your service.

When you want to control who can access your web API.
When you need a simple way to identify and limit users.
When building public APIs that require basic security.
When you want to track usage by different clients.
When you want to block unauthorized access easily.
Syntax
Flask
from flask import Flask, request, jsonify

app = Flask(__name__)

API_KEY = 'your-secret-api-key'

@app.route('/data')
def get_data():
    key = request.headers.get('x-api-key')
    if key == API_KEY:
        return jsonify({'message': 'Access granted', 'data': [1, 2, 3]})
    else:
        return jsonify({'error': 'Unauthorized'}), 401

The API key is usually sent in the request headers for security.

Check the key on every request to protect your endpoints.

Examples
Basic check of API key from request headers.
Flask
key = request.headers.get('x-api-key')
if key == API_KEY:
    # allow access
else:
    # deny access
API key passed as a URL query parameter (less secure).
Flask
@app.route('/info')
def info():
    key = request.args.get('api_key')
    if key == API_KEY:
        return 'Info data'
    return 'Unauthorized', 401
Sample Program

This Flask app has one route that checks for a correct API key in the headers. If the key matches, it returns secret data. Otherwise, it returns an error.

Flask
from flask import Flask, request, jsonify

app = Flask(__name__)

API_KEY = '12345abcde'

@app.route('/secret-data')
def secret_data():
    api_key = request.headers.get('x-api-key')
    if api_key == API_KEY:
        return jsonify({'message': 'Welcome! Here is your secret data.', 'data': [10, 20, 30]})
    else:
        return jsonify({'error': 'Unauthorized access'}), 401

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Never expose your API key in public code or client-side apps.

Use HTTPS to keep the API key safe during transmission.

Consider rotating keys regularly for better security.

Summary

API key authentication is a simple way to protect your API.

Clients send a secret key with each request to prove they are allowed.

Always check the key on the server before giving access.