Building RESTful APIs with FastAPI
Last Updated :
24 Apr, 2025
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 a basic ToDo List API using FastAPI. FastAPI is a Python web framework known for its simplicity and speed, making it a great choice for beginners.
Setting up the Project
Before we start, make sure you have Python installed on your computer. You'll also need to install FastAPI and Uvicorn, For creating API using FastAPI we need fastAPI, also for running the server we also need a uvicorn.
We can install them by running the below command
pip install fastapi
pip install uvicorn
Setting Up FastAPI Application
- Creating a Directory/Folder: We start by creating a new directory/folder for our project. we can name it something like "todoAPI".
- Creating a Python File: Inside your project directory/folder, create a Python file named main.py. This will be the main entry point for our FastAPI application.
So our project structure is now set for writing the actual code to create API using fastAPI.
Creating FastAPI App
Here we have created the FastAPI app.
Python3
from fastapi import FastAPI
app = FastAPI()
Defining ToDo Model
Let's define a simple ToDo model that represents each task. here we simple define Task model which has 2 field title and discription both are of type string.
Python3
from pydantic import BaseModel
class Task(BaseModel):
title: str
description: str = ""
Creating Endpoints for ToDo List
In this step we will create diff - diff endpoints for managing our ToDo list. Here we have to make sure we follow the syntax for creating endpoint for diff diff request type such as GET and POST request.
Here we use simple python list tasks as our data structure to store data.
Python3
Endpoint 1: Add a Task in ToDo List
Here in this endpoint whenever end user do POST request on '/tasks/' we will add that task in tasks list and simply return the msg "msg": "task added succesfully" as response
Python3
@app.post("/tasks/")
def create_task(task: Task):
tasks.append(task)
return {"msg": "task added succesfully"}
Endpoint 2: Get All Tasks
Here we add an endpoint to retrieve all taske by sending GET request to '/tasks/'
Python3
@app.get("/tasks/", response_model=List[Task])
def get_tasks():
return tasks
Endpoint 3: Get a Specific Task
We create an endpoint to retrieve a specific task by it's index in the list, here we user send GET request to '/tasks/indexOfTask' we send that task details in response to the user.
Python3
@app.get("/tasks/{task_id}", response_model=Task)
def get_task(task_id: int):
if 0 <= task_id < len(tasks):
return tasks[task_id]
else:
raise HTTPException(status_code=404, detail="Task not found")
Here we had also added HTTPException because when user send some specific task ID and that task is not in our dataBase we send an error message that "Task not found".
Endpoint 4: Update a Task
In this endpint we had Implement an endponint to update a task specific task with it's task_id. here not that user is sending a PUT request to endpoint "/tasks/{task_id}"
Python3
@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, updated_task: Task):
if 0 <= task_id < len(tasks):
tasks[task_id] = updated_task
return updated_task
else:
raise HTTPException(status_code=404, detail="Task not found")
Endpoint 5: Delete a specific Task
In this endpoint we will implement the deletion functionality, by task_id user can delete a specific task from the Tasks list.
Python3
@app.delete("/tasks/{task_id}", response_model=Task)
def delete_task(task_id: int):
if 0 <= task_id < len(tasks):
deleted_task = tasks.pop(task_id)
return deleted_task
else:
raise HTTPException(status_code=404, detail="Task not found")
Complete Code
The provided code is a FastAPI application for managing tasks with CRUD operations:
- Create a new task with a title and description.
- Retrieve a list of all tasks.
- Get a single task by its ID.
- Update an existing task by its ID.
- Delete a task by its ID.
The application uses an in-memory list as a database to store tasks. It runs on http://127.0.0.1:8000. You can interact with it using API client tools or by sending HTTP requests to the defined endpoints.
Python3
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
import uvicorn
app = FastAPI()
class Task(BaseModel):
title: str
description: str = ""
tasks = []
@app.post("/tasks/")
def create_task(task: Task):
tasks.append(task)
return {"msg": "task added succesfully"}
@app.get("/tasks/", response_model=List[Task])
def get_tasks():
return tasks
@app.get("/tasks/{task_id}", response_model=Task)
def get_task(task_id: int):
if 0 <= task_id < len(tasks):
return tasks[task_id]
else:
raise HTTPException(status_code=404, detail="Task not found")
@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, updated_task: Task):
if 0 <= task_id < len(tasks):
tasks[task_id] = updated_task
return updated_task
else:
raise HTTPException(status_code=404, detail="Task not found")
@app.delete("/tasks/{task_id}", response_model=Task)
def delete_task(task_id: int):
if 0 <= task_id < len(tasks):
deleted_task = tasks.pop(task_id)
return deleted_task
else:
raise HTTPException(status_code=404, detail="Task not found")
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
Deployement of the Project
Most of the developer use postman as tool to test an API we will also use the same. Here are some sample API requests we can make to test our created API endpoints:
Creating a Task
POST http://localhost:8000/tasks/
Body: {"title": "title of task", "description": "description of task"}
Get All Tasks:
GET http://localhost:8000/tasks/
Get a Specific Task (replace {task_id} with the task index):
GET http://localhost:8000/tasks/{task_id}
Update a Task (replace {task_id} with the task index):
PUT http://localhost:8000/tasks/{task_id}
Body: {"title": "updated title"}
Delete a Task (replace {task_id} with the task index):
DELETE http://localhost:8000/tasks/{task_id}
Output:
Adding the tasks 0:
adding task 0 with POST requestAdding the tasks 1:
adding task 1 using POST requestAdding the tasks 2:
adding task 2 with POST requestAccessing all the tasks
accessing all tasks by GET requestAccessing specific tasks with id
accessing specific task with task_id=1 and GET requestUpdating the tasks
updating task where task_id=2 using PUT requestAccessing the updated tasks
accessing all updated task after updating task where task_id=2 using GET requestDeleting the tasks
deleting task where task_id=0 using DELETE requestAccesing the task after deleting
Accessing all task after deleting task where task_id=0 using GET request
Similar Reads
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
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
5 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
Spring Boot â Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions th
5 min read
Building Mock APIs with Swagger
This step-by-step tutorial for constructing a mock API in Python using Swagger. In this article, we'll step through the full process, from defining our API with Swagger to developing and testing a mock server. Whether you're an experienced developer or just starting started, this article will show y
8 min read
Build APIs with Falcon in Python
In the sector of web development, building a sturdy and green API is vital. APIs (Application Programming Interfaces) act as a bridge between software program structures, allowing for easy verbal exchange and record change. Python, with its flexibility and flexibility, is a popular choice for growin
6 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
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
Navigating API Testing with Postman
API(Application Programming Interface) testing plays a pivotal role in the software development lifecycle, ensuring the seamless functionality of APIs and safeguarding against potential issues. Postman, a comprehensive API development and testing tool, offers a range of features to streamline and en
6 min read
Automating API Testing with Postman
Testing the functionality, dependability, and performance of an API is known as API testing. API testing can be done automatically or manually. The technique of automating the execution of API tests with tools is known as automated API testing. This can save time and effort, as well as ensure that A
5 min read