Implementing CRUD operations with FastAPI
Step 1: Make sure your system has Python installed if not follow this article.
Step 2: Install FastAPI, Uvicorn and SQLalchemy using following command.
pip install fastapi uvicorn sqlalchemy
Step 3: Create new file, name main.py
main.py: This code creates a FastAPI web app with SQLAlchemy for CRUD operations on an “items” table in a SQLite database. It provides four endpoints for Create, Read, Update, and Delete operations. The app can be run using uvicorn
.
Python3
import uvicorn from fastapi import FastAPI from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # Database configurations SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit = False , autoflush = False , bind = engine) Base = declarative_base() # SQLAlchemy models class Item(Base): __tablename__ = "items" id = Column(Integer, primary_key = True , index = True ) name = Column(String, index = True ) description = Column(String, index = True ) Base.metadata.create_all(bind = engine) # FastAPI app instance app = FastAPI() # CRUD operations # Create (Create) @app .post( "/items/" ) async def create_item(name: str , description: str ): db = SessionLocal() db_item = Item(name = name, description = description) db.add(db_item) db.commit() db.refresh(db_item) return db_item # Read (GET) @app .get( "/items/{item_id}" ) async def read_item(item_id: int ): db = SessionLocal() item = db.query(Item). filter (Item. id = = item_id).first() return item # Update (PUT) @app .put( "/items/{item_id}" ) async def update_item(item_id: int , name: str , description: str ): db = SessionLocal() db_item = db.query(Item). filter (Item. id = = item_id).first() db_item.name = name db_item.description = description db.commit() return db_item # Delete (DELETE) @app .delete( "/items/{item_id}" ) async def delete_item(item_id: int ): db = SessionLocal() db_item = db.query(Item). filter (Item. id = = item_id).first() db.delete(db_item) db.commit() return { "message" : "Item deleted successfully" } if __name__ = = "__main__" : uvicorn.run(app) |
Testing
To run the application using uvicorn use the command:
uvicorn test:app
Output:
Now let’s start with testing of our API using SwaggerUI. Open new tab in your browser and type http://127.0.0.1:8000/docs
POST Request
Click on POST which will allows us to add items, then click on ‘Try it out‘ top right corner. In request body enter data then click on execute.
GET Request:
On the same page goto GET to retrieve data, then click of ‘Try it out‘. Then click on execute, below in server response you will get all retrieved data. We can also check our users from our 1st tab i.e http://127.0.0.1:8000/items/1. If no changes are reflected try to reload the tab.
PUT Request:
To update your existing user details go to PUT then, enter the index of user present in the list and update details in request body. To check if again use GET method or just go to your path.
DELETE Request:
To delete your existing user, go to DELETE then, enter the index of user present in the list and click execute. Again check if user got deleted or not. You can also in Reponse Body where you will get message like “Item deleted successfully”
Conclusion
Therefore now we can conclude that we can perform CRUD operations using FastAPI which is micro-web-framerwork of python for API development with SQLalchemy for database in which we used Uvicorn for running the API and SwaggerUI for testing our API.
FastAPI – Crud Operations
We will explore how to implement CRUD operations with FastAPI. CRUD operations are essential in any web application, including creating new records, retrieving existing records, updating existing records, and deleting records from a database.
Contact Us