7.4 API Key 认证:查询参数、请求头、Cookie
Python FastAPI API Key Authentication Tutorial for Beginners - Query Params, Headers, Cookies
A beginner-friendly tutorial on implementing API Key authentication in FastAPI using query parameters, request headers, and cookies. Learn with easy step-by-step examples and practical code snippets for Python newcomers.
FastAPI API Key Authentication for Python Beginners
Introduction
Welcome to the world of web development with FastAPI! If you know basic Python but haven't built websites or APIs before, you're in the right place. Think of an API (Application Programming Interface) as a menu at a restaurant—it lists what you can order, and you use an API key as your "secret password" to prove you're allowed to order. In this tutorial, we'll learn how to use API keys in three common ways, just like showing a key to unlock a door in different situations.
By the end, you'll have a working FastAPI app that checks API keys, giving you quick wins to boost your confidence.
Getting Started: Install FastAPI
First, let's set up your environment. You'll need Python installed (version 3.7 or higher). Open your terminal or command prompt and run:
pip install fastapi uvicorn
fastapi is the framework we'll use, and uvicorn is a server to run our app—imagine it as the engine that powers your website car.
Your First FastAPI App: A Quick Success
Let's create a simple app to see FastAPI in action. Create a new Python file called main.py and add this code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
def hello():
return {"message": "Hello, FastAPI!"}
Save it, then run the server:
uvicorn main:app --reload
Open your browser and go to http://127.0.0.1:8000/hello. You should see a JSON response: {"message": "Hello, FastAPI!"}. Congratulations! You just built your first API endpoint. This is your first "success moment"—see how easy it is?
Now, let's add API key authentication to protect this endpoint.
API Key Authentication Methods
Imagine you're guarding a clubhouse. Members need to show a key to enter, and they can do it in different ways. We'll cover three methods: query parameters, request headers, and cookies.
1. Using Query Parameters
Analogy: Think of a query parameter like telling a friend the password over the phone as part of the conversation. It's part of the URL.
In this method, the API key is included in the URL, e.g., http://127.0.0.1:8000/hello?api_key=secret123.
Let's modify our main.py to check for an API key in the query.
from fastapi import FastAPI, HTTPException
app = FastAPI()
# A simple hardcoded API key for demonstration
VALID_API_KEY = "mysecretkey123"
@app.get("/hello")
def hello(api_key: str = None): # api_key is a query parameter
if api_key != VALID_API_KEY:
raise HTTPException(status_code=401, detail="Invalid API Key")
return {"message": "Hello, authenticated user!"}
Restart the server (if it's not auto-reloading, run uvicorn main:app --reload again). Now, try accessing:
- Without API key:
http://127.0.0.1:8000/hello– you'll get an error. - With valid key:
http://127.0.0.1:8000/hello?api_key=mysecretkey123– you'll see the success message.
This is a quick win! You've just added basic security.
2. Using Request Headers
Analogy: Headers are like wearing a badge or ID card—it's extra information sent with your request, not in the URL.
In this method, the API key is sent in the HTTP headers, typically as X-API-Key: mysecretkey123.
Update your main.py:
from fastapi import FastAPI, HTTPException, Header
app = FastAPI()
VALID_API_KEY = "mysecretkey123"
@app.get("/hello-header")
def hello_header(x_api_key: str = Header(None)): # x_api_key is a header
if x_api_key != VALID_API_KEY:
raise HTTPException(status_code=401, detail="Invalid API Key in header")
return {"message": "Hello from headers!"}
To test this, you'll need a tool that lets you set headers, like Postman or even a simple Python script. Here's a quick Python test:
import requests
response = requests.get("http://127.0.0.1:8000/hello-header", headers={"X-API-Key": "mysecretkey123"})
print(response.json())
Run this in a separate Python file, and you should see the success message. Another success moment!
3. Using Cookies
Analogy: Cookies are like a membership card stored in your browser—it's sent automatically with requests to the same site.
In this method, the API key is stored in a cookie.
Update main.py:
from fastapi import FastAPI, HTTPException, Cookie
app = FastAPI()
VALID_API_KEY = "mysecretkey123"
@app.get("/hello-cookie")
def hello_cookie(api_key: str = Cookie(None)): # api_key is a cookie
if api_key != VALID_API_KEY:
raise HTTPException(status_code=401, detail="Invalid API Key in cookie")
return {"message": "Hello from cookies!"}
To test cookies, you need to set a cookie first. Let's create a simple endpoint to set the cookie:
from fastapi import FastAPI, Response
app = FastAPI()
VALID_API_KEY = "mysecretkey123"
@app.get("/set-cookie")
def set_cookie(response: Response):
response.set_cookie(key="api_key", value=VALID_API_KEY)
return {"message": "Cookie set! Now try /hello-cookie"}
@app.get("/hello-cookie")
def hello_cookie(api_key: str = Cookie(None)):
if api_key != VALID_API_KEY:
raise HTTPException(status_code=401, detail="Invalid API Key in cookie")
return {"message": "Hello from cookies!"}
Now, in your browser:
- Go to
http://127.0.0.1:8000/set-cookieto set the cookie. - Then go to
http://127.0.0.1:8000/hello-cookie– you should see the success message.
Boom! You've handled cookies. Feel the progress?
Putting It All Together
Let's create a comprehensive example that uses all three methods, so you can choose based on your needs.
from fastapi import FastAPI, HTTPException, Header, Cookie, Query
app = FastAPI()
VALID_API_KEY = "mysecretkey123"
@app.get("/secure-hello")
def secure_hello(
api_key_query: str = Query(None, alias="api_key"), # query parameter
x_api_key: str = Header(None), # header
api_key_cookie: str = Cookie(None, alias="api_key") # cookie
):
# Check API key from any source
api_key = api_key_query or x_api_key or api_key_cookie
if api_key != VALID_API_KEY:
raise HTTPException(status_code=401, detail="Invalid or missing API Key")
return {"message": "Hello, securely authenticated!"}
This endpoint accepts API keys from query params, headers, or cookies. Test it with different methods to see it work. For example:
- Query:
http://127.0.0.1:8000/secure-hello?api_key=mysecretkey123 - Header: Use a tool with
X-API-Key: mysecretkey123 - Cookie: Set the cookie first as shown earlier.
You've just built a flexible authentication system!
Conclusion
Great job! You've learned how to implement API key authentication in FastAPI using query parameters, request headers, and cookies. Remember:
- Query parameters are simple but visible in URLs.
- Headers are more secure for sensitive data.
- Cookies are great for browser-based apps.
Keep practicing by adding more endpoints or experimenting with different keys. FastAPI makes web development fun and easy—you're on your way to building cool APIs!
For next steps, explore FastAPI's documentation on dependencies and security to handle API keys more robustly. Happy coding!