Fast API: Create Middleware
Let us look at how we can create a middleware for our FastApi project without installing other packages. Middleware are very important for complex logic and really important for security.
Why Do we need to Create Middleware?
Middleware plays a crucial role in building robust and efficient backend routes for several reasons. It allows you to break down complex logic into smaller, reusable functions. This promotes modularity making you code cleaner, easier to understand, and maintain.
With middleware's you can implement features like authentication, rate limiting, logging, monitoring, caching, and data validation through dedicated middle functions.
How can we implement middle to FastAPI?
First, we have to setup our project first. For this tutorial I created a folder called pthon-create-middle-ware
and I used pyenv to set version 3.12
for my project.
mkdir python-create-middle-ware
pyenv local 3.12.0
Then lets create a venv
by running python3.12 -m venv venv
and lets activate our python environment.
python3.12 -m venv venv
source venv/bin/activate
Then open this project on your editor. I will use VS Code.
Inside our project lets install fastapi.
pip install fastapi
and we also need uvicorn for running our application
pip install "uvicorn[standard]"
Let us create our main.py to the root folder of our project.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
Then run
uvicorn main:app --reload
You should see result by opening http://127.0.0.1:8000
to your browser.
Now, that is worknig lets create a folder called middleware
and we will place our middlewares.py
to that folder. With this middleware we can then add our own logic, this middleware will going to run whenever a request is made.
# middleware/middleware.py
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
class AppMiddleware(BaseHTTPMiddleware):
def __init__(
self,
app,
some_attribute: str,
):
super().__init__(app)
self.some_attribute = some_attribute
async def dispatch(self, request: Request, call_next):
# do something with the request object, for example
content_type = request.headers.get('Content-Type')
print(content_type)
# process the request and get the response
response = await call_next(request)
return response
Then in our main.py
we can then add our middleware using add_middle function like so.
from fastapi import FastAPI
from middleware.middleware import AppMiddleware
app = FastAPI()
app.add_middleware(AppMiddleware, some_attribute="some value")
@app.get("/")
def read_root():
return {"Hello": "World"}
Why Fast API
FastAPI has become a popular choice for building web APIs in Python for several reasons.
Built on top of Starlette and Pydantic, FastAPI delivers excellent performance comparable to Node.js and Go frameworks. This makes it ideal for handling high-traffic APIs or applications requiring fast response times.
Inspired by Flask, FastAPI aims for simplicity and clarity. Its syntax is clean and intuitive, making it easier to learn and pick up, even for developers new to building APIs.
FastAPI automatically generates OpenAPI documentation based on your code, eliminating the need for manual documentation writing. This saves time and ensures your API documentation is always up-to-date.
Pydantic integration allows you to define data models and perform automatic data validation for incoming requests and outgoing responses. This helps prevent invalid data from entering your system and ensures consistent data formats.
Built-in asynchronous support means your application can handle multiple requests concurrently, improving scalability and resource utilization. This is particularly valuable for applications dealing with long-running tasks or I/O operations.
FastAPI offers built-in features like dependency injection, CSRF protection, and JWT authentication, helping you secure your APIs from common attacks.
FastAPI boasts a rapidly growing community and ecosystem of libraries, tools, and tutorials. This makes it easy to find solutions for various needs and integrate with other technologies.
While following certain conventions, FastAPI offers flexibility in how you structure your application. You can leverage external libraries and tools seamlessly within your API implementation.
Overall, FastAPI offers a compelling combination of speed, ease of use, developer-friendly features, and a vibrant community, making it a strong choice for building modern and robust web APIs in Python.
If you enjoy this article and would like to show your support, you can easily do so by buying me a coffee. Your contribution is greatly appreciated!