FastAPI Mastery: Building CRUD Apps Made Simple
Muhammad Abu Bakar
Software Engineer || Python || Django || React || Full Stack Developer
Are you ready to take your web development skills to the next level? With FastAPI, building scalable CRUD applications has never been simpler. In this guide, we’ll take you on a journey from beginner to master, equipping you with the knowledge and tools you need to build robust web applications with ease. Fasten your seatbelt, and let’s dive into the world of FastAPI Mastery!
First Of all, you need to set up your environment for the app. you need to install uvicron, and Fastapi in your environment. Then You need to create a main file in which your main server is running. You need to create your app and run your server on the port so that you can see your project and what you are doing. you can see your output. Your main file looks like this. The below get_session is used to connect with the database. when we need to create a connection a connection with the database we’ll use that function.
The return function is returning Docs because of FastAPI Build API automatically in swagger. You can switch to Docs to view Your Documentation of the API.
from typing import List
from fastapi import Depends, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from starlette.responses import RedirectResponse
from sqlalchemy.orm import Session
import models,schemas
from db import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
allow_credentials=True,
)
# Dependency
def get_session():
try:
session = SessionLocal()
yield session
finally:
session.close()
@app.get("/")
def main():
return RedirectResponse(url="/docs/")
Then you need to create a connection with the database you are going to use in the project.
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker#Create sqlite engine instance
engine = create_engine("sqlite:///teacher.db")#Create declaritive base meta instance
Base = declarative_base()#Create session local class for session maker
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
In this code, we create a connection with the database which creates a database for the project if it is not created. Then We are using base Class which we’ll later use in building our models.
领英推荐
class Teacher(Base):
__tablename__ = 'teachers'
id = Column(Integer, primary_key=True)
name = Column(String(256))
age = Column(Integer)
birthday = Column(DateTime)
gender = Column(String(256))
address = Column(String(256))
city = Column(String(256))
Then we need to create a Schemas file. In the Schemas file we define the database schemas that we are using in our models. Basically, we inherit BaseModel then We define our schema.
class Teacher(BaseModel):
id: int
name: str
age: int
birthday: datetime
gender :str
address: str
city: str
After Creating these Files we need to call these files in the main file so that we can run our server Properly. we import these files into our main file and perform our task and create Crud. Here is an Example Of Crud in which we are creating teachers in the database then we are getting those teachers from the Db, then we are Updating and deleting them.
@app.post("/create-teacher/")
def create_teacher(teacher:schemas.Teacher, session = Depends(get_session)):
id = models.Teacher(id=teacher.id)
name = models.Teacher(name=teacher.name)
age = models.Teacher(age=teacher.age)
birthday=models.Teacher(birthday=teacher.birthday)
gender = models.Teacher(gender=teacher.gender)
address = models.Teacher(address=teacher.address)
city = models.Teacher(city=teacher.city)
session.add(name,age)
session.add(birthday,gender)
session.add(address,city)
session.commit()
return id
@app.get('/get-teacher/')
def get_teacher(session: Session = Depends(get_session)):
teacher = session.query(models.Teacher).all()
return teacher
@app.get('/get-teacher/{id}')
def get_teacher_by_id(id: int,session: Session = Depends(get_session)):
teacher = session.query(models.Teacher).filter(models.Teacher.id == id).first()
return teacher
@app.put('/update-teacher/{id}')
def update_teacher(id:int,teacher:schemas.Teacher,session:Session = Depends(get_session)):
up_teacher = session.query(models.Teacher).get(id)
up_teacher.name = teacher.name
up_teacher.age = teacher.age
up_teacher.birthday = teacher.birthday
up_teacher.gender = teacher.gender
up_teacher.address = teacher.address
up_teacher.city = teacher.city
session.add(up_teacher)
session.commit()
print(up_teacher)
return up_teacher
@app.delete('/delete-teacher/{id}')
def delete_teacher(id:int, session=Depends(get_session)):
teacher = session.query(models.Teacher).get(id)
session.delete(teacher)
session.commit()
session.close()
return 'deleted'
In conclusion, the development of CRUD applications is an essential part of building scalable and efficient web applications. With the help of FastAPI, developers can build these applications with ease, and in this article, we have covered the fundamental concepts of building CRUD applications using FastAPI.
We started by setting up FastAPI, and then we explored how to build a basic CRUD application using FastAPI and SQLAlchemy. We also covered how to test the application, integrate Swagger UI for API documentation, and handle errors in the application.
FastAPI has gained a lot of popularity among developers, and for a good reason. Its performance, ease of use, and support for async programming make it an excellent choice for building modern web applications.
With this article, I hope I have provided a good introduction to building CRUD applications using FastAPI and inspired developers to explore this amazing framework further. Happy coding!