FastAPI

 




Installing fast api is easy pip install fastapi[all]

create main.py python file

import FastAPI

create app instance

end point or path or Routing is very easy in FastAPI just Write a path operation decorator (like @app.get("/")

@app.get("/") is a base path

@app.get("/about") is a about path

instead of get method we can also create post, put and delete method

we can even call that method as operation


the function above which we are using operation are called path operation function

and the decorator @app is called path operation decorator


write a path operation function (like def root(): ... above)

Run the development server (like uvicorn main:app --reload)

here main is module or file name and app is instance of FastAPI


@app.get("") def root(): return {"key": "value"}



@app.get("/items/{item_id}") async def read_item(item_id:int): return {"item_id": item_id}



With the FASTAPI we get:

  • Editor support: error check, autocompletion etc
  • Data parsing
  • Data Validation
  • API annotation and automatic documentation

Path parameter
In fast api we can use new feature of python
we can define the data type (using parameter) of variable using colon along with variable
define the type for parameter
for example
 def show(id: int):
    #show is function

Fast API has amazing feature of providing automatic documentation using swagger UI and redoc as well


Query Parameters

there are 3 query parameters:

  • needy, a required str.
  • skip, an int with a default value of 0.
  • limit, an optional int.
from browser we can send multiple query parameter using ? along with URL



For debugging purpose we can simply put the break point in vs code and 
run the program using ctrl+shift+p and search for debug and 

Request body
if we need to send data from client we can send from request body
for that we must declare request body we must use Pydantic models

Pydantic is a library that is going to hold the all the data validation 

first we must include class BaseModel

from pydantic import BaseModel

Pydantic Schemas
Fast API doesn't require us to use SQL(relational) database but we can use any relational database we want

using SQL Alchemy
we use ORM (object relational mapping) which is very good technique

from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL='sqlite:///./dbname.db'
engine=create_engine(SQLALCHEMY_DATABASE_URL,connect_args={"check_same_thread":False})
SessionLocal=sessionmaker(bind=engine,autocommit=False,autoflush=False)
base=declarative_base()





Then make models
model should import from sqlalchemy and base from database model
we can make class like in django here we can give table name (__tablename__)
inside the class


once we have created the models.py
we can migrate the table in main.py file
by
models.Base.meatadata.create_all(engine)

pass db instance in path operation function
db must be of pydentic type Session = Depends(get_db)


fast api contain different other functionalities like status,Response,
HTTPException and many more

Response Model

You can declare the model for the response with the parameter response_model in any of the path operations
  • @app.get
  • @app.post
  • @app.put
  • @app.delete
pydentic model is called schema
and sqlalchemy model is simply called model


if our application is big we will have a better folder structure





Comments