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.PNG

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

Install

pip install fastapi uvicorn

Create an app

from fastapi import FastAPI
app = FastAPI()

Run the app

# save the file as main.py
# 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 http://127.0.0.1:9999 (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

@app.get("/")
def root():
    return {"message": "welcome to FastAPI"}

Second endpoint - returns current time

@app.get("/time")
def get_time():
    return ctime()

Let's build third endpoint with data validation

from  pydantic import BaseModel

class Item(BaseModel):
    name: str

@app.post("/name")
def reverse_name(item: Item):
    return item.name[::-1]

Let's test these endpoints

❯ curl -X POST "http://localhost:9999/name" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{\"name\":\"amalshaji\"}"
"ijahslama"
❯ 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.

swagger.PNG

Conclusion

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).

References

https://fastapi.tiangolo.com/

No Comments Yet