Developing high-performing applications with Python’s FastAPI
Tags: webdev, programming, tutorial, python
Published: 2022-07-28 08:43:00

Python is extremely popular among professionals, and used all over the globe. It is an object-oriented programming language with a dynamic semantic.

But what makes this programming language that popular? 

FastAPI is one of the reasons.

According to the findings of JetBrains, web development is one of the programming language’s most popular use cases.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k54gpel8u0k6yt0gtnxx.png)

Python is mostly chosen for developing [web apps](https://www.abtosoftware.com/web-development-solutions) because of its many additional libraries, helpful frameworks, and simplicity.

## Python’s FastAPI in brief

Let’s look closer at one of the fastest Python web frameworks available.

**Combining Python and FastAPI leads to amazing results and chances to develop fast websites.** FastAPI is a modern, fast (high-performant), web framework with built-in support for async endpoints for building APIs with Python 3.6+ based on standard Python-type hints.

FastAPI was developed by Sebastián Ramírez. First stable release was on December 5, 2018 and the last one on May 10, 2022. 

It was written in Python, and last year FastAPI was recognized as the third most loved web framework in [Stack Overflow 2021 Developer Survey](https://insights.stackoverflow.com/survey/2021/#section-most-loved-dreaded-and-wanted-web-frameworks).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpcpilk6rl3gihhsx4ng.png)

It is used by large companies like Uber and Netflix to develop some of their applications.

## The benefits of using Python’s FastAPI
FastAPI gives the following benefits:

1. Open standards
FastAPI is based on open standards such as [OpenAPI](https://github.com/OAI/OpenAPI-Specification) for API creation, including declarations of path operations, body requests, parameters, security, and more.
2. Interactive documentation
Interactive API documentation and exploration web user interfaces. Two included by default: [Swagger UI, ReDoc](https://github.com/swagger-api/swagger-ui).
3. Standard Python
It’s all based on standard Python 3.6 type declarations. No new syntax to learn. Just standard modern Python.
4. Editor support: auto-completion works everywhere
5. FastAPI is Short
It has sensible defaults for everything, with optional configurations everywhere. All the parameters can be fine-tuned to do what you need and to define the API you need.
6. Validation
FastAPI uses Python type annotations. So you get it out-of-the-box with no need to use additional layer for validation.  
7. Security and authentication integrated
HTTP Basic, OAuth2 (also with JWT tokens), API keys in Headers, Query parameters, Cookies, etc.
8. Dependency Injection
FastAPI comes with its own built-in dependency injection system that helps to integrate components when building your API.
9. Unlimited plugin support
10. FastAPI is thoroughly tested

## How to work with Python’s FastAPI?

Check it out with the following examples.

**The installation**
The first step is to install base packages we are going to work with:
`pip install fastapi uvicorn[standard]
`
**Creating a base class**
Let’s create a class for FastAPIServer:

```py
from fastapi import FastAPI   

from hypercorn.asyncio import serve

from hypercorn.config import Config as HyperCornConfig

from application.actions.action_handler import ActionHandler

class FastAPIServer:


    def __init__(self, action_handler: ActionHandler):

        self._hypercorn_config = HyperCornConfig()

        self._fastapi = FastAPI()

        self._ action_handler =  action_handler


    async def run_server(self):

        self._hypercorn_config.bind = ['0.0.0.0:8081']

        self.add_routes()

       await serve(self._fastapi, self._hypercorn_config)


    def add_routes(self):

        self._fastapi.add_api_route(path="/", endpoint=self.say_hello, methods=["GET"])
```
**Dependency injection**
Add ‘say_hello’ function with authentication to the FastAPIServer:

```py
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/login")
```
You should add the path operation function and mount it to the path **/api/login/**.
Also we can add HTTPException and raise it from the endpoint:

```py
from fastapi import HTTPException

credentials_exception = HTTPException(

    status_code=status.HTTP_401_UNAUTHORIZED,

    detail="Could not validate credentials",

    headers={"WWW-Authenticate": "Bearer"},

)
```

```py
from fastapi import Depends

   ...

async def say_hello(self, token: str = Depends(oauth2_scheme)):    

    current_user = await self.get_current_user(token)

    if current_user is False:

        raise self.credentials_exception
```
Dependency injection is very useful when you need to have shared logic (the same code logic again and again); share database connections; enforce security, authentication (as shown in the example), role requirements, etc.  

**Path and Query parameters**
You can mount a few endpoints to the same path by using additional parameters. 

For example:

```py
self._fastapi.add_api_route(path="/profiles", endpoint=self.get_profiles_list, methods=["GET"])

    self._fastapi.add_api_route(path="/profiles/me", endpoint=self.get_my_profile, methods=["GET"])

    self._fastapi.add_api_route(path="/profiles/{user_id}", endpoint=self.get_user_profile, methods=["GET"])
```
Path operations are evaluated in order, so if you put “/profiles/{user_id}” above “/profiles/me”, **me** will be tracked as **user_id**. 

**user_id** is called path parameters. It can be declared with type or without it:

```py
async def get_user_profile(self, user_id: int):    
 
      …
 
async def get_user_profile(self, user_id):

```
As a parameter type can be used any of standard Python types or [Pydantic types](https://pydantic-docs.helpmanual.io/usage/types/).

Except path parameters you can use Query parameter. Take a look:

```py
from fastapi import Query

...

async def get_profiles_list(

    self,

    search_text: str = Query(None, alias='search-text')

):    

      …

```
**Adding CORSMiddleware**
If your back-end server and web are running on the different ‘origins’ you should add CORS (Cross-Origin Resource Sharing) to your FastAPI server. It can be done by using middleware which is also supported by FastAPI.

```py
from fastapi.middleware.cors import CORSMiddleware


self._fastapi.add_middleware(

   CORSMiddleware,

   allow_origins=["*"],

   allow_credentials=True,

   allow_methods=["*"],

   allow_headers=["*"],

)

```

## Why choose Python’s FastAPI?

FastAPI is the best solution for developing web applications using third-party inside path operation function, or for applications with [microservices’ architecture](https://www.abtosoftware.com/blog/devops-for-fintech-how-to-build-secure-and-scalable-microservices-architecture-using-kubernetes-aws-etc). Such an API will be very fast because when your app receives the request and starts processing it in the microservice, or by passing data to some other API, it should wait for a response. Asynchronous supports the processing of other requests during the time when the system is waiting for a response.

Our team at Abto Software utilizes Python software development for fast prototyping and building highly scalable web applications. Fullstack Python web development services and client-server programming & administration are what we do on a daily basis. 

To name: 
- Data science 
- Big data analysis solutions
- High-load web portals
- Data-driven ERP systems
- Cloud-based solutions
- APIs and automation plugins
and more.