FastAPI

Apr 25, 2022by, Jinu John Veyccan

Uncategorized

FastAPI is a high-performance web framework for building APIs with Python 3.6+ based on standard Python type hints.Fast API claims to be one of the fastest web frameworks on par with Go and Nodejs.

The automatic documentation is also included in FastAPI. Since it is based on python,it provides python type hints for autocompletion and type checks. 

FastAPI is based on two key Python libraries : Starlette(used for web handling) and Pydantic(used for data handling). FastAPI is based on standard integrations like OpenAPI, JSON Schema, OAuth2.

Key features of FastAPI :

  • One of the fastest python frameworks
  • Fast to code
  • Fewer bugs: Reduction in human errors
  • Intuitive: It has autocompletion and editor support
  • Easy to learn
  • Minimize code duplication. 
  • Robust: Get production-ready code. 
  • Compatible with the open standards for APIs

Installation

 pip install fastapi

Below is an example of  an endpoint is defined in FastAPI.

main.py

FastAPI comes with uvicorn which is an ASGI server.

So to run the main.py, you need to use:

uvicorn main:app –reload

Here we provide the file name(main.py) and the class object (app) as arguments. — reload is added so that it reloads on every change.

 (Hypercorn can also be used)

The Swagger UI interface is used by FastAPI to offer an API document engine. Visit  http://127.0.0.1:8000/docs automatic interactive API documentation (provided by Swagger UI) or go to http://127.0.0.1:8000/redoc to see the alternative automatic documentation (provided by ReDoc):

http://127.0.0.1:8000/docs

http://127.0.0.1:8000/redoc 

Passing Parameters

  1. Path Parameters

Suppose we need to fetch a user by ID. We define it as:

Here the path param is accepted as an int, and response is returned as a dict (the whole schema is returned).

If you provide a string as the path param instead of int, it returns an error message. Writing a separate validator for such validations is not required in FastAPI. 

2. Query Parameters

To pass query strings to the API, we use optional (from typing import Optional)


Just like the path parameter, it returns an error message if the input type is not as mentioned in the API definition.

Response Model

If you don’t need the entire model in JSON format in the response, you can declare the model used for the response with the parameter response_model in any of the path operations:

Here password is excluded from UserOut model. UserOut is given as reponse_model in API endpoint definition. 

Response_model_exclude can also be used for the same purpose.


BaseModel is imported from the Pydantic library.

For schema definition/data validation, it uses Pydantic library. The input validation is dealt by FastAPI. If any of the input request parameters is not in the expected form,an appropriate error code will be returned. Instead of returning Internal Server Error(500), if the email field includes an int, a suitable error code will be returned.

Asynchronous execution

The inability to process requests asynchronously was one of the greatest drawbacks of Python WSGI web frameworks compared to Node.js or Go. With ASGI, this can be achieved, and FastAPI takes full advantage of it. Adding the async keyword to the endpoint definition makes the whole thing asynchronous.

Error handling

FastAPI provides HTTPException class for error handling.

With FastAPI, custom headers can also be set.

Dependency injections 

To handle dependencies in API endpoints, it is strongly advised to use the built-in injection system.


The get_database function is evaluated by FastAPI at runtime when the endpoint is called, so the return value can be set to any value according to the need. We do this so that:

  1. The app.dependency_overrides dictionary can be modified to override dependencies globally. This would simplify the testing procedure.
  2. More advanced checks can be performed by the dependency (get database), allowing you to decouple them from business logic.

Integration with databases

Adding a database to your stack is as straightforward as feasible with FastAPI. (Not the web framework’s complexities, but the database you choose will impact how much work is to be done.)

REST can be a major barrier when working with complex data models. It’s not fun when a minor change in the frontend necessitates upgrading an endpoint’s schema. GraphQL shines in these situations. Graphene and FastAPI operate together seamlessly, despite the fact that GraphQL support is not unique among Python web frameworks.