Build a simple API using FastAPI

Recently this tweet by the author of FastAPI triggered a debate on the internet whether "years of experience=skill level".


FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is relatively young, but many organizations are already making the switch. FastAPI documentation says >Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available. - FastAPI documentation


pip install fastapi uvicorn

Create an app

from fastapi import FastAPI
app = FastAPI()

Run the app

# save the file as
# now run the app
uvicorn main:app --reload --port 9999

And you should see something like

❯ uvicorn main:app --reload --port 9999
INFO:     Uvicorn running on (Press CTRL+C to quit)
INFO:     Started reloader process [1021] using statreload
INFO:     Started server process [1023]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Here main and app in main:app should be changed to your_filename:variable_that_is_FastAPI()_instance

--reload will detect changes in file and reloads the server(and yes.... we don't do this for production server)

First endpoint

def root():
    return {"message": "welcome to FastAPI"}

Second endpoint - returns current time

def get_time():
    return ctime()

Let's build third endpoint with data validation

from  pydantic import BaseModel

class Item(BaseModel):
    name: str"/name")
def reverse_name(item: Item):

Let's test these endpoints

❯ curl -X POST "http://localhost:9999/name" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{\"name\":\"amalshaji\"}"
❯ curl "http://localhost:9999/"
{"message":"welcome to FastAPI"}
❯ curl "http://localhost:9999/time"
"Sun Aug  9 15:35:45 2020"

FastAPI also gives you a better way to test your APIs. Just navigate to http://localhost:9999/docs to see automatic API documentation generated using swagger UI. It also gives you the ability to test API without external clients.



There are a lot of features of FastAPI that haven't been covered in this blog(I'll try to write about them soon). FastAPI is very fast, easy to code and the inbuilt data validation support helps reduce a lot of code. It also claims to be 2-3 times faster than Flask, which is a goto API development micro framework(not for long).


No Comments Yet