FastAPI web Framework
Create simple CRUD application in FastAPI framework beginner-friendly
FastAPI is a web framework for developing web applications. It builds on top of Starlette and Pydantic. Starlette handles HTTP requests, and Pydantic is used for data and type validations. I am trying to make tutorial very, very simple so that anyone can learn and start coding
- It is fast.
- Built-in swagger.
- Use AGI (Asynchronous Server Gateway Interface).
Installation
In order to work with fastAPI, we need to install the FastAPI, Uvicorn, and pydantic libraries
pip install fastapi uvicorn pydanticCreate the first program
from fastapi import FastAPI
api= FastAPI()
@api.get("/")
def users():
return 'Hello'Save this file.
Here we import FastAPI, create an object of FastAPI, and assign it to api variable.
We use this api variable to take requests using @ with that and define the type of request.
Run the program
uvicorn <filename>:<object-name> — — reload
uvicorn main:app --reloadUse localhost:8000 to run in a browser.
For the Swagger document: localhost:8000/docs
Path Parameter
A path parameter is an endpoint of a web URL.
from fastapi import FastAPI
api= FastAPI()
@api.get("/user/{id}")
def userDetail(id):
return idRun using localhost:8000/user/1
Get Akshay’s stories in your inbox
Join Medium for free to get updates from this writer.
Validation:
We can add validation by using typing library
from fastapi import FastAPI
from typing import Annotated
api= FastAPI()
@api.get("/hello/{id}")
def userDetail(id: Annotated[int, Path(len=3)]):
return idQuery Parameter
The query parameter is defined in the function only
from fastapi import FastAPI
api= FastAPI()
@api.get("/user")
def userDetail(id):
return idWe can use swagger for this query parameter or define in the URL by localhost:8000/user?id=1
POST
The POST method is the way to send and store new data. Pydantic is a prerequisite to use this method. We need to create a Pydantic model.
from fastapi import FastAPI
from pydantic import BaseModel
class User(BaseModel):
name:str
age:int
height:int
api= FastAPI()
@api.post("/save")
def save(user: User):
## perforn operations to store values in file or db
return JSONResponse(status_code=200, content=user.model_dump_json())We can test by using Postman or Swagger docs. We pass values in JSON format. http://localhost:8000/docs
PUT
PUT is being used for updating data.
from fastapi import FastAPI
from pydantic import BaseModel
class User(BaseModel):
name:str
age:int
height:int
api= FastAPI()
@api.put("/update/{id}")
def save(id:int, user: User):
## perforn operations to update values in file or db
return JSONResponse(status_code=200, content=user.model_dump_json())DELETE
The delete method is being used for deleting data.
from fastapi import FastAPI
api= FastAPI()
@api.delete("/delete/{id}")
def delete(id:int):
## perforn operations to delete values in file or db
return JSONResponse(status_code=200, content=['Deleted'])






