Book Image

Building Python Web APIs with FastAPI

By : Abdulazeez Abdulazeez Adeshina
Book Image

Building Python Web APIs with FastAPI

By: Abdulazeez Abdulazeez Adeshina

Overview of this book

RESTful web services are commonly used to create APIs for web-based applications owing to their light weight and high scalability. This book will show you how FastAPI, a high-performance web framework for building RESTful APIs in Python, allows you to build robust web APIs that are simple and intuitive and makes it easy to build quickly with very little boilerplate code. This book will help you set up a FastAPI application in no time and show you how to use FastAPI to build a REST API that receives and responds to user requests. You’ll go on to learn how to handle routing and authentication while working with databases in a FastAPI application. The book walks you through the four key areas: building and using routes for create, read, update, and delete (CRUD) operations; connecting the application to SQL and NoSQL databases; securing the application built; and deploying your application locally or to a cloud environment. By the end of this book, you’ll have developed a solid understanding of the FastAPI framework and be able to build and deploy robust REST APIs.
Table of Contents (14 chapters)
Part 1: An Introduction to FastAPI
Part 2: Building and Securing FastAPI Applications
Part 3: Testing And Deploying FastAPI Applications

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 = [