I have been working with Flask recently and have been quite comfortable with it, but recently I got a chance to work with FastAPI in Python and it is way easier to configure things in FastAPI as compared to Flask.
The below article just talks about setting up basic apps using FastAPI, and you can see for yourself how easy it is.
Step 1. Once you have the folder ready, open it in Visual Studio and install the FastAPI package.
pip install "fastapi[standard]"
The idea is to install FastAPI[standard] and not just FastAPI as the standard version contains support for FastAPI commands and also other composite packages.
Step 2. Once you have it installed create a new file, main.py, and perform the below steps.
- Import FastAPI.
- Create a FastAPI object.
from fastapi import FastAPI
app = FastAPI()
- Once, this is done, create a basic get request which returns a JSON of a Hello greeting message.
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def read_data():
return {"Hello": "There!"}
- Run the solution using the below command.
fastapi dev main.py
This gives an option of testing the api using swagger at http://127.0.0.1:8000/docs, another great thing about FastAPI.
There is also a new api testing ui available at http://127.0.0.1:8000/redoc.
Step 3. Let's go ahead and add more endpoints, for the post as well as another get with input parameters.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.get('/')
def read_data():
return {"Hello": "There!"}
@app.get('/personalized_greeting/{name}')
def personalized_greering(name: str):
return {"Hello": name}
@app.post('/post_name')
async def post_name(item: Item):
return item
On running the solution, the swagger UI is as below.
The non-swagger ui looks like below.
I hope this article helps!