The topic for today is about four advanced features in FastAPI that might be useful in your web application. If you are new to FastAPI, it is highly recommended to follow the starter guide provided by the official documentation before you continue.

Moreover, I have covered two FastAPI tutorials on How to Migrate From Flask to FastAPI and Smoothly and Metadata and Additional Responses in FastAPI. Feel free to check them out if you would like to learn more about the tips and tricks related to FastAPI. In this tutorial, I am going to explain the fundamental concepts behind:

  • Request — Using the Request object directly to get client address, request body, cookies, and etc.
  • Event handlers — Register functions to be executed when the application starts or when the application shutdowns.
  • Environment variables — Handle configurations and settings related to your project.
  • WSGIMiddleware — Include your Flask or Django server as sub application inside FastAPI.

1. Request

The Request object in FastAPI is based off Starlette’s Request with additional tools on top of it. In fact, you can use it directly inside your path operation function to get details such as the client’s IP address. Have a look at the following code snippet. The API will return the client’s host and port when you call it.

from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/client-data")
def client_data(request: Request):
    client_host = request.client.host
    client_port = request.client.port

    return {"client_host": client_host, "client_port": client_port}

Based on the official documentation, Request object has the following commonly used fields:

  • Method — Accessible via request.method.
  • URL — Accessible via request.url. Contains other components such as request.url.pathrequest.url.portrequest.url.scheme.
  • Headers — Accessible via request.headers. Components are exposed as immutable, case-insensitive multi-dict. For example, you can use request.headers[‘content-type’] to get Content-Type from the header.
  • Query Parameters — Accessible via request.query_params. Just like Headers, you can access the query parameters using request.query_params['search']
  • Path Parameters — Accessible via request.path_params. Parameters are exposed as multi-dict. For example, request.path_params['name']
  • Client Address — Accessible via request.client. Holds a named two-tuple for host and port. You can get the details via request.client.host and request.client.port.
  • Cookies — Cookies are based on dictionary interface. You can access the fields inside it using request.cookies.get('mycookie').
  • Body — The returning body consists of multiple interfaces based on your use cases. For getting the bytes data, you can use request.body(). Form data or multipart are sent as request.form(). Besides, you can parse the input as JSON using request.json().

#python #flask #programming #devops #fastapi

4 Useful Advanced Features in FastAPI
3.50 GEEK