FastAPI: Build REST API in 5 minutes

Maybe we know FastAPI is a web framework of python. The meaning of its name expresses what is more special about this framework than others. The very new features of python async and await are here. The API is really fast like nodeJS and Go (They claimed).

The more interesting thing is the implementation time of the REST API. The first endpoint will take at most five minutes to implement including the API docs.

Confused Tom Hanks GIF

What I have discussed here you can find all those things in FastAPI official documentation. It is very rich than other web frameworks in python. Almost everything you can find there.

Let’s try

Create your virtual environment.

Python3 -m venv myenv

Activate it now

Source myenv/bin/activate

Install FastAPI

pip install fastapi

Install uvicorn as ASGI server. The official documentation recommends it.

pip install "uvicorn[standard]"

Now create a file with your API endpoint and app.

my_app.py

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "World"}

Now run the server

uvicorn my_app:app --reload

If the command looks complex to you and you forget it often.

Create another python file and name it runserver.py

import os
os.system("uvicorn my_app:app --reload")

Now you can run the server with the below command.

python runserver.py

Your server will run at this URL: http://127.0.0.1:8000

Open it in your web browser, and you can see 

{"Hello": "World"}

I think it will take less than 5 minutes to implement.

Lets try with passing parameter

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id, "message": {"Hello": "World"}}

Data Model or Serializer

Like DRF serializer, Flask Marshmallow FastAPI used Pydantic as a data model or serializer.

from typing import List, Optional
from pydantic import BaseModel
class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: float = 10.5
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
  return {
        "name": "Baz",
        "description": "There goes my baz",
        "price": 50.2,
        "tax": 10.5,
    }

For post or put requests, you can mention the data model also.

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
  return {"item": item, "item_id": item_id}

FastAPI uses redoc library to create its API auto-generated documentation.

You will find it at this endpoint… http://127.0.0.1:8000/docs#/

Uses of async and await

If you are using third-party libraries

@app.get('/')
async def read_results():
    results = await some_library()
    return results

Note: Make sure your library has this async and await support or write the above function without async and await.

We will discuss more how async and await work in python in a different blog.

Thanks for reading.

Md. Raisul Islam

Software Development Engineer II

Published: July 17, 2023

UPD: July 20, 2023

Get In Touch

Map

The power of Technology

is now at your disposal

Address:

Plot # 272, Lane # 3 (Eastern Road)
DOHS Baridhara, Dhaka 1206

Phone:

+880 1730 3586 45

Email:

Our Experts are Ready to Help You

    captcha

    Contact Us Directly

    Address:

    Plot # 272,
    Lane # 3 (Eastern Road)
    DOHS Baridhara, Dhaka 1206

    Talk to Us

    +880 1730 3586 45