CORS (Cross-Origin Resource Sharing) in FastAPI APIs
Following our lesson on Dependency Injection in FastAPI, this article explains CORS (Cross-Origin Resource Sharing) in FastAPI APIs. CORS is a security feature that browsers implement to control how web pages in one domain can request resources from another domain.
📚 Prerequisites
- A running FastAPI application.
- Basic understanding of web security concepts.
🎯 Article Outline: What You'll Master
- ✅ Foundational Theory: What CORS is and why it's necessary.
- ✅ Core Implementation: Using
CORSMiddlewareto enable CORS in FastAPI. - ✅ Configuration Options: Understanding the different CORS configuration options.
- ✅ Best Practices: Securely configuring CORS for your application.
🧠 Section 1: The Core Concepts of CORS
By default, web browsers restrict cross-origin HTTP requests initiated from scripts. This is known as the Same-Origin Policy. CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.
💻 Section 2: Deep Dive - Implementation and Walkthrough
FastAPI provides a CORSMiddleware to handle CORS.
# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def main():
return {"message": "Hello World"}
Step-by-Step Code Breakdown:
from fastapi.middleware.cors import CORSMiddleware: We import the middleware.origins = [...]: We define a list of allowed origins.app.add_middleware(...): We add theCORSMiddlewareto our application.allow_origins: A list of origins that are allowed to make cross-origin requests.allow_credentials: Indicates that cookies should be supported for cross-origin requests.allow_methods: A list of HTTP methods that are allowed.["*"]allows all methods.allow_headers: A list of HTTP headers that are supported.["*"]allows all headers.
💡 Conclusion & Key Takeaways
You've learned how to enable and configure CORS in your FastAPI application, which is essential for allowing web applications to interact with your API.
Let's summarize the key takeaways:
- CORS is a browser security feature that restricts cross-origin requests.
- FastAPI's
CORSMiddlewaremakes it easy to configure CORS. - It's important to be restrictive in your CORS configuration for security.
➡️ Next Steps
In the next article, "Authentication and Authorization Basics for APIs: JWT (Introduction)", we will learn how to secure our API endpoints.
Glossary
- CORS: Cross-Origin Resource Sharing.
- Origin: The combination of a protocol (e.g.,
http), domain (e.g.,localhost), and port (e.g.,8080). - Same-Origin Policy: A browser security policy that restricts how a document or script loaded from one origin can interact with a resource from another origin.