Open In App

Configuring CORS in FastAPI

Last Updated : 04 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see what is an Origin, what is CORS, and how CORS can be used to enable different origins to access and share resources. We will see why the CORS issue occurs when the frontend and backend is present in different origin and how the browser sends a request to the server.

What is Origin in FastAPI?

An origin is basically the combination of the protocol, domain, and port on which the application is running. So for two urls even if one of the three combinations is different those urls will said to be of a different origin. The following URLs are all said to be of a different origin:

http://localhost

http://localhost:5000

https://localhost:5000

What is CORS in FastAPI?

CORS stands for cross-origin resource sharing. It is a mechanism that allows different origins to access and share resources. Browsers enforce the same origin policy which means you can only send requests to the origin from which you are generated, but in modern applications, different origin needs to share resources. For this CORS is used which allows a standardized way to specify which origins are allowed to access the resources.

How does CORS Mechanism work?

When a web page makes an HTTP request to a different origin, then the browser first makes a preflight request which is used to check whether the given request is allowed by the server or not. The server sends the HTTP OPTIONS request which contains the following headers:

  • Access-Control_Request_Method: It contains the method(PUT, POST, DELETE) that the page wants to send to the server.
  • Access_Control_Request-Headers: It contains the header that the actual request will contain.

The server needs to be configured to handle the OPTIONS request. When the server receives the request it checks whether it will allow the following request or not. The server sends back a set of CORS headers if it approves the request, the main headers include :

  • Access-Control-Allow-Origin : Which specifies the origins which are allowed to access servers resources. It can be a list of origins or can contains * which specifies any origin can access the resources.
  • Access-Control-Allow-Methods : HTTP methods that can make cross origin request to the server.
  • Access-Control-Allow-Header : Headers that are allowed by the server when making cross origin request.

The browser then check the header returned by the server and see whether it can make the request or not. If the request cannot be make it throws an error.

What is CORS Issue?

Consider you have created a web application whose frontend is running on browser at location

http://localhost:8000

and the backend is running at the URL

http://localhost:5000

Now consider the frontend sends an API request to the backend, in this case if the backend is not configured to handle the cross origin requests then the browser will not allow the request to be send to the server and will raise the error on the frontend. For allowing cross-origin requests the server should be configured to have the list of origins and methods that are allowed by the client. So when a cross origin request is raised by the application, a preflight request is send by the browser and the server then send the allowed origin list back to the browser with the help of which browser can now determine whether to proceed with the HTTP request or not.

CORSMiddleware in FastAPI

To allow cross-origin requests you have to configure the server which can be done with the help of CORSMiddleware class which is present in the fastapi module. To import CORSMiddleware class copy paste the below code:

from fastapi.middleware.cors import CORSMiddleware

We have to define the list of origins that are allowed to make the cross origin requests. You can create a list of origin as show below:

Python3




        "http://localhost:8000",
        "https://localhost:5000"
       ]


Now you can use the app_middleware function present in the fastAPI class for defining the CORS configuration, such as the list of origins and methods that are allowed to make the cross origin request. Copy the below code and paste it on the top of your application for CORS.

Python3




from fastapi import fastAPI
from fastapi.middleware.cors import CORSMiddleware
app = fastAPI()
        "http://localhost:8000",
        "https://localhost:5000"
]
app.app_midleware(
  CORSMiddleware,
  allow_origins = list,
  allow_methods = ["*"],
  allow_headers = ["*"]
)


In the above code we specified the origins that are allowed to make the cross origin request, list of methods that are allowed, in our case it is [“*”] which means all the HTTP methods are allowed by the server. The list of header “allow_headers” which can be sent by the client which is also set to [“*”].

Any request that is coming to the server will be intercepted by the middleware, and if the request contains the CORS headers such as Origins and Access-Control_request_Method, the middleware will respond with the CORS headers we defined in the app_middleware function.

Allowing Requests from any Origin

We might want our server to take request coming from any origin rather then to some specific sets of origins, in that case we can just set the value of allow_origins = [“*”] which will allow any cross origin request to hit on the server.

Python3




from fastapi import fastAPI
from fastapi.middleware.cors import CORSMiddleware
app = fastAPI()
app.app_midleware(
  CORSMiddleware,
  allow_origins = ["*"],
  allow_methods = ["*"],
  allow_headers = ["*"]
)


If the server configured with the above code then requests coming from any origin will be allowed by the server. For example if the client is sending request from the origin https://gfg.com:8000 to server running at http:gfgserver.com:7000 the server will allow the request from the client and will run the decorator function for the “/” endpoint.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads