How To Enable CORS In FastAPI In Python?

Introduction

Today we will understand the concept of CORS, its workflow, and the implementation of CORS in our application.

What is FastAPI?

FastAPI is a modern web framework used for building APIs in Python. It is based on the Starlette framework and the Pydantic library and offers many features. FastAPI fully supports asynchronous programming and can run on Gunicorn and ASGI servers such as Uvicorn, making it a good choice for production environments.

For more detail on FastAPI, read this article- Getting Started With FastAPI.

Installation

pip install fastapi uvicorn  

Code

from fastapi import FastAPI
app = FastAPI()
@app.get("/home")
async def home_page():
    return "Hello World!"

The above code provides a basic example of creating an API endpoint using FastAPI.

Command to run the above program

python -m uvicorn fast:app --reload

Output

fast_API_output

What is CORS?

Cross-Origin Resource Sharing (CORS) occurs when a frontend program running on one client browser attempts to connect with a backend using JavaScript code, and the backend is in a different "origin" than the front end. The source is a mix of protocol, domain name, and port numbers. This enables secure communication between browsers and servers from a different source.

Note- CORS adds another layer of security to ensure that only trusted domains can access your site's resources.

How does CORS work?

CORS works by adding additional HTTP headers to the list of standard headers. When the client submits a request to the server, CORS is added to the header.

CORS_workflow

reference -https://blog.devgenius.io/cors-101-72b462396deb

How to use CORSMiddleware?

CORSMiddleware is a class that implements the CORS protocol as a middleware component for FastAPI applications.

Code

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
   "http://localhost:8080"
]
app.add_middleware(
   CORSMiddleware,
   allow_origins=origins,
   allow_credentials=True,
   allow_methods=["*"],
   allow_headers=["*"],
)
#creating endpoints
@app.get("/home")
async def home_page():
    return "Hello World!"

Explanation

In the above code, the FastAPI library is imported, and the instance of FastAPI is created, named app. The CORSMiddleware is used to handle Cross-Origin requests and allow the specified origin. In this case, http://localhost:8080 is allowed to access the API. Then an endpoint is defined using the @app.get("/home"), which maps the "/home" URL to the home_page() function. When this endpoint is accessed via an HTTP GET request, it will respond with the string Hello World!

What are the Request Headers, and What do they do?

Access control request headers are fairly straightforward and, for the most part, pretty self-explanatory.

  • allow_origins: The (sub)domain that the script making the request was served to the browser from.
  • allow_credentials: A boolean flag that determines whether cookies and authorization headers are permitted for cross-origin requests.
  • allow_methods: The HTTP methods that should be permitted for cross-origin requests.
  • allow_headers: The custom headers that the browser expects to send along with the actual request to follow.

Conclusion

In this article, we learned about CORS and also learned its implementation using FastAPI.

FAQ's

Q. Does CORS protect the server?

A. CORS provides an extra layer of protection by enabling servers and clients.

Q. What happens if you disable CORS?

A. This gives the attackers to access internal sites behind the firewall using cross-communication types of attack.


Recommended Free Ebook
Similar Articles