0% found this document useful (0 votes)
0 views3 pages

New Text Document

This document provides a step-by-step guide to creating an API with Flask and implementing API key authentication. It includes instructions for setting up Flask, creating middleware for API key validation, and defining protected routes, as well as generating API keys. Additionally, it outlines security best practices for production environments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views3 pages

New Text Document

This document provides a step-by-step guide to creating an API with Flask and implementing API key authentication. It includes instructions for setting up Flask, creating middleware for API key validation, and defining protected routes, as well as generating API keys. Additionally, it outlines security best practices for production environments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

To create an API with Flask and implement API key authentication, follow these

steps:

### 1. Install Flask


```bash
pip install Flask
```

### 2. Create a Basic Flask App


```python
from flask import Flask, jsonify, request
import uuid # For generating API keys

app = Flask(__name__)

# In-memory storage for API keys (use a database in production)


valid_api_keys = {}

# Helper function to generate API keys


def generate_api_key():
return str(uuid.uuid4())
```

### 3. Create API Key Authentication Middleware


```python
def api_key_required(func):
def wrapper(*args, **kwargs):
api_key = request.headers.get('X-API-Key')
if not api_key or api_key not in valid_api_keys:
return jsonify({"error": "Unauthorized"}), 401
return func(*args, **kwargs)
wrapper.__name__ = func.__name__
return wrapper
```

### 4. Create Protected API Endpoints


```python
@app.route('/protected', methods=['GET'])
@api_key_required
def protected_route():
return jsonify({"message": "Welcome! You have access to this protected
route."})

# Add more endpoints as needed


```

### 5. Create an API Key Generation Endpoint (Optional)


```python
@app.route('/generate-key', methods=['POST'])
def generate_key():
# Add authentication for this endpoint in production
new_key = generate_api_key()
valid_api_keys[new_key] = True # Store key with metadata (e.g., user ID)
return jsonify({"api_key": new_key}), 201
```

### 6. Run the Flask App


```python
if __name__ == '__main__':
app.run(debug=True) # Turn off debug in production
```

---

### Full Example Code (`app.py`)


```python
from flask import Flask, jsonify, request
import uuid

app = Flask(__name__)
valid_api_keys = {}

def generate_api_key():
return str(uuid.uuid4())

def api_key_required(func):
def wrapper(*args, **kwargs):
api_key = request.headers.get('X-API-Key')
if not api_key or api_key not in valid_api_keys:
return jsonify({"error": "Unauthorized"}), 401
return func(*args, **kwargs)
wrapper.__name__ = func.__name__
return wrapper

@app.route('/generate-key', methods=['POST'])
def generate_key():
new_key = generate_api_key()
valid_api_keys[new_key] = True
return jsonify({"api_key": new_key}), 201

@app.route('/protected', methods=['GET'])
@api_key_required
def protected_route():
return jsonify({"message": "Access granted!"})

if __name__ == '__main__':
app.run(debug=True)
```

---

### How to Use the API

1. **Generate an API Key**:


```bash
curl -X POST http://localhost:5000/generate-key
```
Response:
```json
{"api_key": "a1b2c3d4-e5f6-7890-g1h2-i3j4k5l6m7n8"}
```

2. **Access Protected Route**:


```bash
curl -H "X-API-Key: YOUR_API_KEY" http://localhost:5000/protected
```
Successful Response:
```json
{"message": "Access granted!"}
```

---

### Security Best Practices


1. **Use HTTPS** in production to encrypt traffic.
2. **Store API keys securely** (hash keys in a database instead of using in-memory
storage).
3. **Add rate limiting** to prevent abuse.
4. **Include additional metadata** (e.g., expiration date, user ID) with API keys.
5. **Rotate keys** periodically for sensitive applications.

For production, consider using libraries like `Flask-HTTPAuth` or `Flask-JWT` for


more advanced authentication.

You might also like