Configuring CORS
Cross-Origin Resource Sharing (CORS) serves as a rule that prevents unregistered clients access to a resource.
When our web API is consumed by a frontend application, the browser will not allow cross-origin HTTP requests. This means that resources can only be accessed from the exact origin as the API or origins permitted by the API.
FastAPI provides a CORS middleware, CORSMiddleware
, that allows us to register domains which can access our API. The middleware takes an array of origins which will be permitted to access the resources on the server.
What is a middleware?
A middleware is a function that acts as an intermediary between an operation. In web APIs, a middleware serves as an mediator in a request-response operation.
For example, to allow only Packt to access our API, we define the URLs in the origin array:
origins = [ “http://packtpub.com”, “https://packtpub.com”...