|
| 1 | +# FastAPI Day 07: Middleware and CORS |
| 2 | + |
| 3 | +Welcome to **Day 07** of the FastAPI tutorial! Today, you'll learn how to use middleware to intercept and process requests and responses, and how to configure Cross-Origin Resource Sharing (CORS) to allow your frontend applications to communicate with your API. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## What You'll Learn |
| 8 | + |
| 9 | +- Understand what middleware is and how it processes requests and responses. |
| 10 | +- Implement custom middleware for logging, performance monitoring, and adding custom headers. |
| 11 | +- Understand the importance of Cross-Origin Resource Sharing (CORS) for web applications. |
| 12 | +- Configure CORS middleware to securely allow frontend clients to access your API. |
| 13 | +- See how middleware is added to a FastAPI application and how the order matters. |
| 14 | + |
| 15 | +--- |
| 16 | + |
| 17 | +## Key Concepts |
| 18 | + |
| 19 | +### 1. What is Middleware? |
| 20 | + |
| 21 | +**Middleware** is a function that works with every request before it is processed by a specific path operation and with every response before it is returned. It acts as a processing layer that can inspect, modify, or even block requests and responses. |
| 22 | + |
| 23 | +Think of it like an onion with layers. A request travels inward through each layer of middleware to the application's core, and the response travels outward through the same layers in reverse order. |
| 24 | + |
| 25 | +In FastAPI, you create middleware using the `@app.middleware("http")` decorator. |
| 26 | + |
| 27 | +### 2. Implementing Custom Middleware |
| 28 | + |
| 29 | +You can create your own middleware to add custom functionality. A common use case is to log requests, add a processing time header, or handle custom authentication schemes. |
| 30 | + |
| 31 | +A middleware function receives two arguments: |
| 32 | +- `request: Request`: The incoming request object. |
| 33 | +- `call_next`: A function that receives the `request` and passes it to the next middleware or the actual path operation. |
| 34 | + |
| 35 | +Example of a custom middleware that adds a `X-Process-Time` header to every response: |
| 36 | +```python |
| 37 | +# from src/main.py |
| 38 | + |
| 39 | +import time |
| 40 | +from fastapi import FastAPI, Request |
| 41 | + |
| 42 | +app = FastAPI() |
| 43 | + |
| 44 | +@app.middleware("http") |
| 45 | +async def add_process_time_header(request: Request, call_next): |
| 46 | + start_time = time.time() |
| 47 | + response = await call_next(request) |
| 48 | + process_time = time.time() - start_time |
| 49 | + response.headers["X-Process-Time"] = str(process_time) |
| 50 | + return response |
| 51 | +``` |
| 52 | +This middleware records the time before passing the request on, waits for the response, calculates the total time, and injects a new header into the response before returning it. |
| 53 | + |
| 54 | +### 3. Cross-Origin Resource Sharing (CORS) |
| 55 | + |
| 56 | +**CORS** is a browser security feature that restricts a web page from making requests to a different domain, protocol, or port than the one that served the web page. This is known as the "same-origin policy." |
| 57 | + |
| 58 | +In modern web development, it's very common to have a frontend (like a React or Vue app) running on a different domain (e.g., `localhost:3000`) than your backend API (e.g., `localhost:8000`). Without proper CORS configuration on your API, the browser will block requests from your frontend, preventing your application from working. |
| 59 | + |
| 60 | +### 4. Configuring CORS Middleware in FastAPI |
| 61 | + |
| 62 | +FastAPI provides a `CORSMiddleware` to handle this easily. You import it, add it to your application, and configure which origins, methods, and headers are allowed. |
| 63 | + |
| 64 | +Example configuration from `src/main.py`: |
| 65 | +```python |
| 66 | +# from src/main.py |
| 67 | + |
| 68 | +from fastapi.middleware.cors import CORSMiddleware |
| 69 | + |
| 70 | +app = FastAPI() |
| 71 | + |
| 72 | +origins = [ |
| 73 | + "http://localhost", |
| 74 | + "http://localhost:3000", |
| 75 | + "http://127.0.0.1:5500" # Example for Live Server in VS Code |
| 76 | +] |
| 77 | + |
| 78 | +app.add_middleware( |
| 79 | + CORSMiddleware, |
| 80 | + allow_origins=origins, |
| 81 | + allow_credentials=True, |
| 82 | + allow_methods=["*"], # Allows all standard methods |
| 83 | + allow_headers=["*"], # Allows all headers |
| 84 | +) |
| 85 | +``` |
| 86 | +This configuration allows web pages served from the specified origins to make requests to your API. |
| 87 | + |
| 88 | +--- |
| 89 | + |
| 90 | +## Next Steps |
| 91 | + |
| 92 | +- Explore the `src/main.py` file to see how the `CORSMiddleware` and a custom timing middleware are implemented. |
| 93 | +- Run the application and use a tool like `curl -v http://localhost:8000/` or your browser's developer tools to inspect the response headers. You should see the `X-Process-Time` header. |
| 94 | +- Create a simple `index.html` file and use JavaScript's `fetch()` to make a request to your running API. Open the HTML file from your file system or a local server to see CORS in action. |
| 95 | +- Try removing one of the origins from the `allow_origins` list and see how the browser blocks the request. |
| 96 | + |
| 97 | +--- |
| 98 | + |
| 99 | +**Tip:** Correctly configuring CORS is essential for building full-stack applications. Always be as specific as possible with `allow_origins` in a production environment to maintain security. |
| 100 | + |
| 101 | +--- |
0 commit comments