Creating First REST API with FastAPI
FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, we’ll walk you through the steps to create your very first REST API using FastAPI. By the end, you’ll have a solid foundation for building and deploying APIs with ease.
What is FastAPI?
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use, efficient, and reliable, making it a popular choice for developing RESTful APIs and web applications. FastAPI has gained popularity due to its simplicity, automatic documentation generation, and excellent performance.
Features of FastAPI :
- High Performance than many Web Frameworks, faster than Node.js, etc.
- Easy to Develop APIs
- Production Ready
- Well Documentation to learn code fast
- Swagger UI to form API Documentation
- Avoid Redundancy of Code
- Easy Testing
- Support for GraphQL, Background Fetching, Dependency Injection
CREATING REST API USING FastAPI
Creating a REST API with FastAPI involves defining endpoints for different HTTP method GET and handling requests and responses using Python functions. Below, I’ll provide a step-by-step guide to creating a simple REST API using FastAPI.
pip install fastapi
Install the uvicorn which is the Asynchronous Gateway Interface for your Server using :
pip install uvicorn
Now create a main.py file and import fastapi, also create a server
Python3
from fastapi import FastAPI app = FastAPI() |
Now, let’s add the code for sample get request as shown below :
Python3
@app .get( "/" ) def read_root(): return { "Hello" : "World" } |
Hence, the main.py file will look like :
Python3
from fastapi import FastAPI app = FastAPI() @app .get( "/" ) def first_example(): ''' FG Example First Fast API Example ''' return { "GFG Example" : "FastAPI" } |
Now, start the server using
uvicorn main:app --reload
Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docs You will be able to see the Swagger UI Home page as below :
Expand the “First Example” :
Now try to Execute the API, you will get the success status with 200 code . The Response will be {“GFG Example”: “FastAPI”} as shown below :
and like this if you want to create the all the type of
CRUD operation in FAST API
Create an item in Fast API
Creating an item in FastAPI involves defining a data model for the item, creating an API endpoint to handle POST requests to create the item, and setting up the database to store the item.
Create a post Api to create Item in main.py file.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
# In-memory database (for demonstration purposes)
items = []
# Pydantic model for item data
class Item(BaseModel):
name: str
description: str
# Create an item
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
items.append(item)
return item
This will create a method to post an item in fast API and with interactive screen provided by FAST Api and start the sever
uvicorn main:app --reload
and when we click on the excute button our API will get executed and get the output as shown in the picture.
Get an item in Fast API
To retrieve (GET) an item in FastAPI, you need to create an API endpoint that handles GET requests for a specific item. Here’s how you can do it step by step
As we created an item above using post API now to get that item we can create an get API to get the item and add the code to the above code
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
if item_id < 0 or item_id >= len(items):
raise HTTPException(status_code=404, detail="Item not found")
return items[item_id]
and when we click on the excute button our API will get executed and get the output as shown in the picture.
Update an item in Fast API
To update (PUT) an item in FastAPI, you need to create an API endpoint that handles PUT requests to modify an existing item.
Import the required modules and set up your FastAPI app, including the database configuration (assuming you have already defined the Item model and database session as shown in previous examples
Add the below code the main.py to create a put API with Fast API
# Update an item
@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, item: Item):
if item_id < 0 or item_id >= len(items):
raise HTTPException(status_code=404, detail="Item not found")
items[item_id] = item
return item
Now we update the name of the item from ABHISHEK SHKAYA to ABHISHEK SHAKYA-NEW and hit execute and the API will update the item name from ABHISHEK SHKAKYA to ABHISHEK SHAKYA-NEW and we get the output as shown.
Delete an item in Fast API
To delete an item in FastAPI, you need to create an API endpoint that handles DELETE requests for a specific item.
Import the required modules and set up your FastAPI app, including the database configuration (assuming you have already defined the Item model and database session as shown in previous examples
Add the below code to the main.py to delete the item from the model in FAST API
# Delete an item
@app.delete("/items/{item_id}", response_model=Item)
async def delete_item(item_id: int):
if item_id < 0 or item_id >= len(items):
raise HTTPException(status_code=404, detail="Item not found")
deleted_item = items.pop(item_id)
return deleted_item
pass the id of the item you want to delete in my case which is 0.
and when we click on the excute button our API will get executed and give the output as shown in the picture.
Contact Us