FastAPI - Introduction (API on the FLY)

FastAPI - Introduction (API on the FLY)

I have writing about APIs a lot as they are truly powering the backend by giving the flexibility to write complex applications in your favored languages of programming. Writing core logic in Python and JS is what I love as I am currently most used to the language.

Many backend frameworks have been disrupting the industry by giving developers the power. Some of the Popular Backend frameworks are:-

Python:-

  1. Flask
  2. Django
  3. FastAPI

JS:-

  1. Node (Cannot say this as the framework)
  2. Express

Today we will go through FastAPI, I will try to give a holistic view of what is it like to use this and what power does it give that other Python Frameworks don't.

KEY FEATURES: As per the official docs

  1. Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic).
  2. Fast to code: Increase the speed to develop features by about 200% to 300%.
  3. Fewer bugs: Reduce about 40% of human (developer) induced errors.
  4. Intuitive: Great editor support. Completion everywhere. Less time debugging.
  5. Easy: Designed to be easy to use and learn. Less time reading docs.
  6. Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
  7. Robust: Get production-ready code. With automatic interactive documentation.
  8. Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.

Being used at Uber, Microsoft, Netflix.

What will we do in this is make a simple Todo Application having features such as

  • View all the Todo
  • Update any Todo
  • Delete any Todo
  • Create any Todo

Step 1:-

Install FastAPI

  • pip install fastapi
  • pip install uvicorn

Now just without any second thought create a main.py file and add in the following code stub in that:-

from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

and run the following command from the terminal to verify if the fastapi is working fine on your system.

uvicorn main:app --reload

Step 2:-

Now we start with an app to make a Todo backend application. We will be using pydanitc for our BaseModel where we define the types:

  • Importing Libraries:-
from fastapi import FastAPI, Depends
from pydantic import BaseModel
from starlette.requests import Request
import json
  • Defining FastAPI app:-
app = FastAPI()
  • Defining a JSON based database:-
database = {
    "Sarvesh": {
        1: {
            "title": "Do Morning Walk",
            "task_content": "We should always go for a walk in the morning"
        }
    }
}
  • Get all the tasks of a particular username:-
@app.get("/tasks/")
async def get_tasks(request: Request):
    username = await request.body()
    username = json.loads(username.decode('utf-8'))
    print(username)
    return database[username["username"]]

JSON body to be sent in the request:- {"username": "Sarvesh"}

  • Update any task of a user:-
@app.post("/update/")
async def update_task(request: Request):
    info = await request.body()
    info = json.loads(info.decode('utf-8'))
    print(info)
    task_id = info["task_id"]
    username = info['username']
    new_content = info["task_content"]
    database[username][task_id]["task_content"] = new_content
    print(database)
    return "Ok"

JSON body to be sent with the request in Postman:- {"username":"Sarvesh", "task_id":1, "task_content": "new_content"}

  • Create a new task for a user:-
@app.put("/add/")
async def create_task(request:Request):
    info = await request.body()
    info = json.loads(info.decode('utf-8'))
    print(info)
    task_id = info['task_id']
    username = info['username']
    content = info["task_content"]
    title = info["title"]

    if(username not in database.keys()):
        database[username] = {}
    database[username][task_id] = {}
    database[username][task_id]["title"] = title
    database[username][task_id]["task_content"] = content

    print(database)
    return True

JSON body to be sent with the request:- {"username":"Sarvesh", "task_id":1, "task_content": "new_content"}, "title": "new title"

  • Delete any task of the user:-
@app.delete("/delete_task/")
async def delete_task(request: Request):
    info = await request.body()
    info = json.loads(info.decode("utf-8"))
    print(info)

    task_id = info['task_id']
    username = info['username']
    del database[username][task_id]

    print(database)

    return "OK"

JSON data to be sent in the request:- {"username":"Sarvesh","task_id":1}

I am adding the whole code here in the Github Repository:- Do give a star if you find it helpful and I will adding in more time on FastAPI to write some more articles.