profile picture

Python FastAPI tutorial - Part 1

August 08, 2020 - python fastapi tutorial

This will be series of tutorials on Python's FastAPI, which is a fast, easy and fun to code rest api framework in Python.

As per their website, FastAPI is as fast as Go and NodeJS (thanks to Starlette and Pydantic), it uses Python standard type hints for validation. And this in turn enables great editor support.

Installation

Using poetry - Recommended

poetry init # to initialize the package, create pyproject.toml file
poetry add fastapi uvicorn # uvicorn is the ASGI server

Using just pip

pip install fastapi uvicorn

A simple hello world example

# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def hello():
    return {"msg": "Hello World!"}

To start the development server use:

# main is the file name and app is the instance of FastAPI
uvicorn main:app --reload

Visit https://localhost:8000/, you will the json response as {"msg": "Hello World!"}

Path Parameters

We can modify above example to take "Name" from the url path.

from fastapi import FastAPI

app = FastAPI()

# https://localhost:8000/John -> {"msg": "Hello John!"}
@app.get("/{name}")
async def hello(name: str):
    return {"msg": f"Hello {name}!"}

The name is a path parameter which it expects to be of string type.

Query Parameters

Query parameters are really simple, i.e. any parameters in the function which are not declared in the path will be treated as query parameter.

from fastapi import FastAPI

app = FastAPI()

# https://localhost:8000/q=John -> {"msg": "Hi, I am John. I like Gintama"}
# https://localhost:8000/q=John&anime="Noragami" -> {"msg": "Hi, I am John. I like Noragami"}
@app.get("/")
async def hello(name: str, anime: str = "Gintama"):
    return {"msg": f"Hi, I am {name}. I like {anime}!"}

In the above example anime is an optional query parameter with default value as Gintama.

That is it for this part. In the next tutorial, we will take a look at Request Body and Pydantic.