Author avatar

Gaurav Singhal

Explore Python Libraries: FastAPI

Gaurav Singhal

  • Jun 29, 2020
  • 8 Min read
  • Jun 29, 2020
  • 8 Min read
Data Analytics
Machine Learning


FastAPI is a modern Python web framework which with a number of advantages, including:

  • It is one of the fastest (high-performance) web frameworks available.
  • It takes advantage of type annotation support of Python 3.6+ for better data validation and editor support.
  • It utilizes Python's Async power, which is useful for building asynchronous APIs.
  • It generates standards based on open standards such as OpenAPI and JSON Schema.
  • It is robust and easy to use and learn.

So in this guide, you will be exploring one of the newest and finest Python web framework libraries.

Getting Started

There are just three basic steps to install, create, and run FastAPI.


1pip install fastapi

You will also need an ASGI (Asynchronous Server Gateway Interface) server such as Uvicorn.

1pip install uvicorn

Create your App

To see what the simplest FastAPI app could look like, create a new Python file called

1from fastapi import FastAPI
3app = FastAPI()
6def read_root():
7    return {"hello": "world"}

Run your App

To run the app, just execute like this :

1uvicorn main:app --reload

After running the above command, the server starts as follows:

1INFO:     Uvicorn running on (Press CTRL
2+C to quit)
3INFO:     Started reloader process [4136] using
5INFO:     Started server process [12988]
6INFO:     Waiting for application startup.
7INFO:     Application startup complete.

Diving Deeper

Path Parameters

You can declare parameters to the API call as variables as a function parameter. Here , I have used course_id as the parameter. Note that the type of the parameter is int.

2def my_course(course_id: int):
3    return {"course_id": course_id}

If you provide the URL incorrectly, say for course/100s, you will get the following validation error.

2    "detail": [
3        {
4            "loc": [
5                "path",
6                "course_id"
7            ],
8            "msg": "value is not a valid integer",
9            "type": "type_error.integer"
10        }
11    ]

And if you run the example for a URL such as course/100, the call will get this response:


Query Parameters

The other way of providing parameters to API calls is by providing them as query parameters. For example: /my/page/items/?page=1&limit=10&order=0.

Here's how you can implement the function in FastAPI.

1dummy_data = [i for i in range(100)]
4async def read_item(page: int = 0, limit: int = 0, skip: int = 1):
5    return dummy_data[page*10: page*10 + limit: skip]

In the above example, there are three parameters set. So for a URL such as, the parameters will be:

  • page(int): 2
  • limit(int): 29
  • skip(int): 2

So the response of the above URL will be:


Request Body

When you need to send data from the client to the server, you can use the request body.

Note: To send data using the request body, use the POST method. You cannot use the GET method in the request body.

To declare a request body, use Pydantic models and declare the request body as:

1from pydantic import BaseModel
3class MyItem(BaseModel):
4    name: str
5    info: str = None
6    price: float
7    qty: int
10async def create_item(item: MyItem):
11    return {"amount": item.qty*100, "success": True}

In the above example, I have created a model named MyItem which has certain attributes. Now when there is a POST request on endpoint /purchase/item/, it will capture the attribute values and return with success.

Let's test this API call using CURL.

1curl -X POST "" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"name\":\"sample item\",\"info\":\"This is info for the item\",\"price\":40,\"qty\":2}"

It will give the response:


Form Data

In many scenarios, you may need to receive form fields instead of JSON. In such cases, Form comes to the rescue. The way that HTML forms (<form></form>) sends data is different from JSON, but FastAPI ensures correct parsing of the data.

To use form data, first install the additional library python-multipart.

1pip install python-multipart

For this demo, I have created a login view, that takes username and password as form fields.

1from fastapi import Form
4async def login_view(username: str = Form(...), password: str = Form(...)):
5    return {"success": True}

Automatic Docs

FastAPI comes with a battery included for automated API documentation in a nice and beautiful web user interface. Two default automatic docs come with fastAPI.

Swagger UI

This is an interactive exploration of your API calls. Here, you can view and test your API calls in a nice, user-friendly interface. Read more here .


Alternatively, you can use redoc for your API documentation.

Check out more about here .

Exploring Features


FastAPI apps running under Uvicorn use one of the fastest Python web frameworks, second only to Starlette and Uvicorn itself (used internally by FastAPI). Check out the benchmarks.

Development Speed

Creating REST API's endpoints with FastAPI takes less than five minutes. It increases the speed of developing features by about 200% to 300%. It's easy to use and learn and requires less time reading docs.


Security and authentication are automatically integrated. All the security schemas defined by OpenAPI and Starlette are included.

Starlette Features

FastAPI is a subclass of Startlette, so almost all of the functionality you have in Starlette works in the same way. Some of the main features include:

  • Websocket support
  • GraphQL support
  • GZip, Static Files, Streaming responses
  • Session and Cookie support

Check out to explore more fastAPI features.


FastAPI is an emerging and relatively new web framework. If you are looking for a fast, light-weight, high-performance web API framework for machine learning, deep learning, or any other project that requires a web application, then FastAPI is the right choice.

In this guide, you explored the FastAPI library, an emerging web framework in Python. Thanks for reading. If you have any questions, feel free to contact me at CodeAlphabet.