Why use FastAPI?
FastAPI is a modern and performant web framework for building APIs. Built by Sebastian Ramirez, it uses the newest features of the Python programming language, such as type hinting and annotations, the async – await syntax, Pydantic models, web socket support, and more.
If you are not familiar with APIs, let’s get into it in more depth by understanding what an API is. An application programming interface (API) is used to enable some kind of interaction between different pieces of software, and they communicate using Hypertext Transfer Protocol (HTTP) through a cycle of requests and responses. Therefore, an API is, as its name suggests, an interface. Via this interface, humans or machines interact with an application or a service. Every API provider should have an interface that is well suited for the type of data that they provide; for instance, a weather forecasting station provides an API that lists the temperatures and humidity levels for a certain location. Sports sites provide statistical data about the games that are being played. A pizza delivery API will provide you with the selected ingredients, the price, and the estimated time of arrival.
APIs touch every aspect of your life, for example, transmitting medical data, enabling fast communications between applications, and even used in tractors in fields. APIs are what make today’s web run and, put simply, are the best form of information exchange.
This chapter will not go over the rigorous definitions of REST APIs, but just list some of their most important features:
- Statelessness: REST APIs are said to be stateless, which means that neither the client nor the server stores any states in between. All the requests and responses are handled by the API server in isolation and without information about the session itself.
- Layered structure: To keep the API scalable and understandable, a RESTful architecture implies a layered structure. The different layers form a hierarchy and communicate with each other but not with every component, thus improving overall security.
- Client-server architecture: APIs should be able to connect different systems/pieces of software without limiting their own functionalities—the server and the client have to stay separate and independent from each other.
There are numerous reasons why MongoDB chose FastAPI for their REST API layer, even though it’s new compared to other Python frameworks. Here are some of the reasons:
- High performance: FastAPI can achieve very high performance, especially compared to other Python-based solutions. By using Starlette under the hood, FastAPI’s performance reaches levels that are usually reserved for Node.js and Go.
- Data validation and simplicity: Being heavily based on Python types and Pydantic brings numerous benefits. Since Pydantic structures are just instances of classes the developers define, you can use complex data validations, deeply nested JSON objects, and hierarchical models (using Python lists and dictionaries), and this relates very well with the nature of MongoDB.
- Faster development: Development becomes more intuitive, with strong integrated development environment (IDE) support, which leads to faster development time and fewer bugs.
- Standards compliance: FastAPI is standard-based and fully compatible with open standards for building APIs—such as OpenAPI and JSON schema.
- Logical structuring of apps: The framework allows the structuring of APIs and apps into multiple routers and allows granular request and response customization, and easy access to every part of the HTTP cycle.
- Async support: FastAPI uses an asynchronous server gateway interface (ASGI) and, with the use of an ASGI-compatible server, such as Uvicorn or Hypercorn, is able to provide a truly asynchronous workflow without actually having to import the
asyncio
module into Python. - Dependency injection: The dependency injection system in FastAPI is one of its biggest selling points. It enables the creation of complex functionalities that are easily reusable across your API. This is a pretty big deal and probably the feature that makes FastAPI ideal for hybrid web apps—it gives developers the opportunity to easily attach different functionalities to the REST endpoints.
- Great documentation: The documentation of the framework itself is excellent and second to none. It is both easy to follow and extensive.
- Automatic documentation: Being based on OpenAPI, FastAPI enables automatic documentation creation, which essentially means that you get your API documented for free with Swagger.
Also, getting started is relatively simple:
pip install fastapi
In order to get at least a basic idea of what coding with FastAPI looks like, let’s take a look at a minimal API:
# main.py from fastapi import FastAPI app = FastAPI() @app.get(“/”) async def root(): return {“message”: “Hello World”}
The preceding few lines of code define a minimal API with a single endpoint (/
) that responds to a GET
request with the message Hello world
. You can instantiate a FastAPI class and use decorators to tell the server which HTTP methods should trigger which function for a response.