Create custom middleware with FastAPI

preview_player
Показать описание
Create custom middleware with FastAPI

What is middleware? Middleware is a layer that pre-processes requests in web servers. Before a request reaches our controllers, i.e. the functions that implement endpoints/URLs in our API, there's a pre-processing stage. In that stage, the framework parses the request, validates the headers, the content type, the data types, and so on.

Most web development frameworks allow us to create custom middleware, and this is incredibly useful to add custom pre-processing components. For example, we may want to check for custom headers in the request. We can also use middleware to handle authorization and authentication, to log requests, to implement rate-limiting/throttling policies, to track user interactions, and more.

We have two ways of creating custom middleware in FastAPI:

- Decorator-based middleware

- Class-based middleware

Decorator-based middleware has a simple and nice interface and it's very convenient for small and simple middleware components. Class-based middleware is suitable for complex components that need to be isolated and encapsulated into their own modules.

In this video, I show you how to create middleware in FastAPI using both approaches. We implement a very simple API, and then we add a simple middleware that checks whether requests have a custom header X-User-Type and its value. It's best practice to prefix customer headers with X- to easily tell them apart from standard headers.

In future videos, I'll show you how to create middleware for Flask and Django, and how to create more complex middleware.

Let me know what you liked and didn't like about this video, and what other topics you'd like me to cover!

00:00 Introduction
02:30 Setting the environment (Poetry)
04:48 Configuring the environment in the DE (Pycharm)
05:35 Creating a hello world endpoint
06:12 Running the API server
07:10 Project requirements
08:32 Types of middleware in FastAPI
08:52 Creating a decorator-based middleware
12:22 Testing the middleware
14:07 Implementing class-based middleware
17:50 Testing the class-based middleware
19:02: Wrapping up

If you liked this video, please like it and share it with your network, and subscribe to my channel!

I'm also the author of the following Manning books:

Let me know also what other kinds of topics you'd like me to address in future videos!
Рекомендации по теме
Комментарии
Автор

Thank you. Simple and sweet. Easy step by step

SamsonJudea
welcome to shbcf.ru