0% found this document useful (0 votes)
3 views16 pages

FASTAPI

FastAPI is a high-level Python framework designed for building APIs, particularly effective for handling large data transfers and integrating with front-end frameworks like React. The document outlines installation steps, application creation, CRUD operations, database connections, and authentication mechanisms using JWT. It also provides examples of routing, path parameters, query parameters, and data validation using Pydantic.

Uploaded by

inkwake2025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

FASTAPI

FastAPI is a high-level Python framework designed for building APIs, particularly effective for handling large data transfers and integrating with front-end frameworks like React. The document outlines installation steps, application creation, CRUD operations, database connections, and authentication mechanisms using JWT. It also provides examples of routing, path parameters, query parameters, and data validation using Pydantic.

Uploaded by

inkwake2025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

FASTAPI

1)it is high level python framework used to bulid api's which is work on the data to
transferring b/w client and server

2)it is little fast to built and to work on api endpoints like get,post,put,delete.

3)It is highly recommended when dealing with huge amount of data which is coming to
website it helps us to integrate with front end framework like react and gives better support
when connecting with node js and go language

4)it gives better support when converting ML data modules to API'S.

STEPS TO INSTALL :

1)In this , need to install framework with minimal and standard modules and need to install
server with minimal or standard modules.

2)To install fastapi


i)pip install fastapi -->(minimal)
ii)pip install "fastapi[standard]"

COMMAND TO INSTALL SERVER(UVICORN):

1)pip install uvicorn -->(minimal)


2)pip install "uvicorn[standard]"
STEPS TO CREATE THE APP

1)activate virtual env


2)create empty folder to store all the applications or examples
3)create a new python module
4)import the fastapi class belongs to fastapi module
from fastapi import FastApi
5)create an application by creating object for fastapi class
app= FastApi()
6)create a function and returns the value which is in form on dictionary and to run that func
decorate with the routing functionalities of http protocol methods like GET,POST,PUT
,DELETE,etc,,,
Eg:
@[Link](“/”)
def index():
return {‘message’:’this is FastApi’}
7.@[Link](‘/’) is routing functionalities of get method which is used to get the information
and we need to provide the path parameters.

8)To run the server


uvicorn filename:app reload

STEPS TO RUN FASTAPI APPLICATION:

• Create a new python module

• In that import the fastapi from FastApi module

• Create a function & decorate with respective rounting configuration. The Routing
configuration such as
[1]. Create- post
[2]. read -get
[3]. Update -put
[4]. delete delete

• Before creating an function, create an Application by creating an object for FastApi


class.
Example:
from fastapi import FastApi
app= FastApi()

@[Link]("/")
def Index():
return { "message": "FastApi “}
NOTE:
• Run the FastApi
• we need to go for UI Swagger of a fastapi need to enter the domain name as follows.
[Link].8000/docs

PATH PARAMETERS:
▪ It is a parameters or path variable associated in a URL configuration
▪ It can be both static or dynamic parameters

i. STATIC PATH PARAMETER:

o It is declared only In Routing configuration and it is


constant and will not change during execution

eg:

@[Link]("/parameter")
def Index ():
return ("menage": "path param")

ii. DYNAMIC PATH PARAMETER:


o It is a parameter which gets The value during Runtime
and it is dynamically Changing

o It is declared both in routing configuration Inside the In


curly braces as well as in function declaration as
follows

Ex:
@[Link]("/parameter/{dynamic_param}")

def Index (dynamic_param):


return ("dynamic_param": "dynamic_param")
QUERY PARAMETERS:
▪ It is parameters which is prefixed with ? and present in the form of key
and value pair.
?key=value
▪ It will be associated at the last of url configuration and need to be
declare only in the function declaration, no need to mentioning routing
configuration.

Example:
@[Link]("/parameter/{specific_value}")

def Index (specific_value:str , another_spec_value : str ):

pass

NOTE
▪ In the above example Specific_value is dynamic path parameter and
another_specific_value is a query parameter

▪ for both parameters Suffixed with :str because we are informing a


application to accept only string type data.

PYDANTIC:
• Pydantic is external module in FastApi which helps in data modelling , data passing ,
data validation , and for serialization .
• It contains BaseModel which helps in give the additional validation steps for the
existing fields in models.
• To give validation steps we need to use field function with respective datatype along
with respective validation type inside the field function
Example:

Class Student:
id:int
name:str
age:int
def __init__(self,id,name,age):
[Link]=id
[Link]=name
[Link]=age

#BaseModel
class StudentRequest(BaseModel):
id:Optional[int] =Field(description=’id not necessary ’, default = None)
name:str=Field(min_length=3)
age: int

#Creating object for Normal Class


Students=[
Student(id=1,name=’aki’,age=22),
Student(id=2,name=’sita’,age=25)
]

NOTE
id:Optional[int] =Field(description=’id not necessary ’, default = None)
In this when we are adding student details ID is not compulsory , when we
adding new student details ID should be incremented automatically .
name:str=Field(min_length=3)
In this , name field will accept string type data and we can give the minimum
number of character need to accept so we need to provide min_length.
marks:int=Field(lt=100,gt=34)
When we are passing any integer values , we can give the range from 1 value
to another by mentioning parameters like lt(less than) and gt(greater than)
skills:List[str]=[]
The above syntax is used to accept list type values if you are not passing
anything it will accept the empty list .

Example:
[Link]
@[Link](‘/’)
def all_students():
return students

[Link]
@[Link](‘/create_student’)
def add_new_student(new_student:StudentRequest):
add_student=Students(**new_student.model_dump())
[Link](find_student_id(add_student))

def find_student_id(std:Student):
if len(students)==0:
[Link]=1
else:
[Link]=students[-1].id+1
return std
1. When we pass new data in UI Swagger using post endpoint it will go for
StudentRequest BaseModel for data validation
2. If the validation is success it will give every data in the form of key and values pair.
3. Dump the data using model_dump method or dict() as a object details to student class
.
4. Before adding to final database need to create new id for the new student details by
calling helper function called find_student_id.
5. Once it returns the new student id , add the details to the database.

FASTAPI DATABASE CONNECTION:


• When we are connecting external database to FastApi need to take a the connection
steps manually one by one
• Installing external module , Installing ORM etc,..
• External module:
pip install pymysql (connect two different s/w)
pip intall sqlalchemy (FastApi ORM Module)

• need to create new database in external DB


• In FastApi, everything need to handle manually step by step by creating database
engine , database url , connection object and cursor object as follows.

[Link]

from sqlalchemy import create_engine


from [Link] import sessionmaker,declarative_base

MYSQL_USER='root'
MYSQL_PASSWORD='root'
MYSQL_HOST='localhost'
MYSQL_PORT=3306
MYSQL_DB='newdb' #db name
DATABASE_URL=(
f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}"
f"@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}"
)

engine=create_engine(DATABASE_URL,echo=True) #Connection object

SessionLocal=sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
) #cursor object

Base=declarative_base()

[Link]
#Create a model with the help of sql alchemy orm classes and methods and by using
base class of database

from sqlalchemy import Column,Integer,String


from database import Base

class User(Base):
__tablename__="users"

id=Column(Integer,primary_key=True,index=True)
name=Column(String(100))
email=Column(String(100),unique=True,index=True)
[Link]
#Create a pydantic BaseModel class to give the validation steps for the existing columns

from pydantic import BaseModel


class UserCreate(BaseModel):
name:str
email:str

class UserResponse(UserCreate):
id:int
class Config:
orm_mode=True

[Link]
#write a CRUD operations code in separate file for creation , modifying and to commit the
changes

from [Link] import Session


import models,schema

#code of POST endpoint


def create_user(db:Session,user:[Link]):
db_user=[Link](
name=[Link],
email=[Link]
)
[Link](db_user)
[Link]()
[Link](db_user)
return db_user

#code of GET endpoints


def get_users(db:Session):
return [Link]([Link]).all()

[Link]
#To run FastApi application we need to have the main business logic to connect each and
every modules .

from fastapi import FastAPI,Depends


from [Link] import Session
import models
from database import engine,SessionLocal
import schema,qry
app =FastAPI()
#create tables
[Link].create_all(bind=engine)
#dependency
def get_db():
db=SessionLocal()
try:
yield db
finally:
[Link]()
STESP TO PERFORM CRUD OPERATION USING DATABASE CONNECTION:
1. Create a respective schema(serializable class) for each operation
2. Create a dependency for each operation before performing .
Dependency includes connection from application to external DB
Query operation
Open connection
Close the connection
POST ENDPOINT:

• It should accept respective schema as a first parameter (userCreate schema),


dependency injection as a second parameter .

Example :

#add reords in db
@[Link]('/users/',response_model=[Link])
def create_user(user:[Link],db:Session=Depends(get_db)):
db_user=[Link](name=[Link],email=[Link])
[Link](db_user)
[Link]()
[Link](db_user)
return db_user

• we are passing the data in the form of dictionary in UI swagger using POST
configuration .
• The data will passed to schema to validate .
• Then validation is success it will create a object and then add it to a DB and
commit the changes and refresh the Database.
TO GET ALL THE USERS:
▪ Create a get endpoint to display all the users data and use userResponse in the form
of the list.
▪ Insert a dependency injection.
▪ Use query() method belongs to database and pass [Link] and use all()
method , it will returns the all the objects details belongs to specific field model.
Example:
@[Link]('/users/',response_model=list[[Link]])
def get_users(db:Session=Depends(get_db)):
return [Link]([Link]).all()

TO GET SINGLE RECORD:


▪ Accept user_id as a dymanic path parameter
▪ Use response schema and dependency injection.

Example :
@[Link]('/usersss/{user_id}', response_model=[Link])
def get_by_id(user_id: int, db: Session = Depends(get_db)):
user = [Link]([Link]).filter([Link] == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user

▪ query() method used to get model objects


▪ filter() method is used to fetch only the single record based on the id.
▪ If user not found , raising HTTPException Error with the status_code of 404
with the message.
PUT ENDPOINTS:
• Need to have user_id , updateSchema and dependency.
• Based on the id , fetch the existing record.
• Update the details from updateSchema to existing record.
• Commit the chsnges nd refresh the database.

Example:
@[Link]('/usss/{user_id}', response_model=[Link])
def get_by_id(user_id: int,user_data:[Link] ,db: Session = Depends(get_db)):
user = [Link]([Link]).filter([Link] == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
[Link]=user_data.email
[Link]=user_data.name
[Link]()
[Link](user)
return user

DELETE ENDPOINT
➢ Delete the existing record based on the Id
➢ Need to have user_id and dependency
➢ Fetch the existing record.
➢ Delete the record using delete method and commit the changes.
Example:
@[Link]('/d/{user_id}')
def dele(user_id,db:Session=Depends(get_db)):
user = [Link]([Link]).filter([Link] == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
[Link](user)
[Link]()
AUTHENTICATION AND AUTHORISATION:

AUTHENTICATION:
It is used to check the given user and users password is
present or not and it is correct or not .
While authenticating we need to generate access tokens for
the respective user details and then need to verify.
To generate the tokens we need to have JWT (JSON Web
Tokens or pyJWT module)
JWT modules helps us to generate access token with the
help of inbuilt modules and functions
It has three parts header,payload,signature.
In this , we need to work on the schemas (BaseModel) for token and
to get the user name using generated token and user BaseModel to get the
complete details.
Need to have the inbuilt functions like verify password , get
password in hash , authenticate user and create access token.
Create a endpoint configurations for login , get_user_details .

LOGIN FOR ACCESS TOKEN:


It should accept user_name and password .
It should authenticate user password after decrypting from database
and once user details is matched , tokens should be generated with the help of
hashing algorithm and in given time .

AUTHORISATION:
It is a mechanism to check logged in user role after the
authentication.
If the user authentication is successful it will generate the tokens
Use the token to authorise the user role in the authorise section in UI Swagger.

You might also like