Creating First REST API with FastAPI
Last Updated :
15 Sep, 2023
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.
Now,Install Python 3 and pip/pip3 according to your Operating System:
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
Creating post API in fast APIand when we click on the excute button our API will get executed and get the output as shown in the picture.
get API responseGet 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]
get method in FAST APIand when we click on the excute button our API will get executed and get the output as shown in the picture.
Response of the get APIUpdate 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.
response of the update API in fast APIDelete 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.
Delete API i fast API and when we click on the excute button our API will get executed and give the output as shown in the picture.
Response of Delete API in fast API
Similar Reads
Building RESTful APIs with FastAPI
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. There is Another famous framework for doing the same is Flask, which is also Python-based. In this article, we will focus on creating a RESTful API using FastAPI. In this article, we will learn how to create
5 min read
Testing FastAPI Application
The web framework in Python that is used for creating modern and fast APIs is called FastAPI. Once we have created the FastAPI, there is a need to test if the API is working fine or not according to the requirements. In this article, we will discuss the various ways to test the FastAPI application.
3 min read
Flask Creating Rest APIs
A REST API (Representational State Transfer API) is a way for applications to communicate over the web using standard HTTP methods. It allows clients (such as web or mobile apps) to interact with a server by sending requests and receiving responses, typically in JSON format.REST APIs follow a statel
4 min read
How to Create Microservices with FastAPI
Creating microservices with FastAPI involves setting up small, independent services that can communicate with each other, usually over HTTP. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. Here's a step-by-step guide
3 min read
Django REST API - CRUD with DRF
Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around the Django Framework. There are three stages before creating an API through the REST framework, Converting a Modelâs data to JSON/XML format (Serialization), Rendering this data to the view, and Cr
7 min read
Comparison of FastAPI with Django and Flask
For starters, as you may know, Python is an interpreted programming language that is becoming more and more popular for building web applications. However, there are numerous web frameworks to choose from but they all have different use cases. In this article, we will look at 3 frameworks which are
4 min read
FastAPI - Rest Architecture
FastAPI is a modern web framework for building APIs with Python. When developing a RESTful API with FastAPI, you can follow a REST architectural style, which stands for Representational State Transfer. In this article, we will learn about the FastAPI-Rest Architecture. Before going let's understand
9 min read
Building APIs using FastAPI with Django
Combining FastAPI and Django can leverage the strengths of both frameworks: FastAPI's high performance for building APIs and Django's powerful ORM and admin interface. In this guide, we'll outline how to integrate FastAPI into a Django project to build high-performance APIs.In this article, we will
2 min read
Building Web App with Django and FastAPI
Django is a powerful and popular web framework for building robust web applications with Python. It comes with a lot of built-in features, including an ORM, an authentication system, and a powerful admin interface. However, there are scenarios where you might want to integrate Django with FastAPI, a
4 min read
Documenting RESTful APIs with Swagger
RESTful APIs play an important role in communicating between various software components. The interface used to consume APIs significantly impacts the chances of achieving business and technological objectives. In this article, we'll dive into the importance of RESTful API documentation and how Swag
8 min read