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():
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 API
and when we click on the excute button our API will get executed and get the output as shown in the picture.

get API response
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]

get method in FAST API
and 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 API
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.

response of the update API in fast API
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.

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
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read