Error Handling in FastAPI
Last Updated :
24 Apr, 2025
A fast and modern Python web framework for building API is known as FastAPI. Like various instances in Python, FastAPI could also give some errors on performing a certain action, for which the user needs to be notified. In this article, we will discuss various ways to handle errors in FastAPI.
What is Error Handling in FastAPI?
Error handling is a crucial aspect of web development when building robust and reliable applications. In the context of FastAPI, a modern web framework for building APIs with Python, understanding and implementing error handling is essential to ensure your API responds gracefully to various situations.
Ways to Handle Errors in FastAPI
- Using HTTP status codes
- Using built-in exception handlers
- Using custom exception handlers
- Using middleware
- Using logging
Error Handling using HTTP Status Codes
The FastAPI provides you with some HTTP status codes that give users information on how the server handled a client request. In this method, we will see how we can handle errors in FastAPI using HTTP status codes. The HTTP status codes are basically grouped into five classes:
|
Informational responses
| 100-199
|
Successful responses
| 200-299
|
Redirection messages
| 300-399
|
Client error responses
| 400-499
|
Server error responses
| 500-599
|
Syntax: def function_name() -> Item:
if condition:
raise HTTPException(status_code=HTTP_Code_1, detail=f"error_message_1")
else:
raise HTTPException(status_code=HTTP_Code_2, detail=f"error_message_2")
Here,
- function_name: It is the function which you want to call while testing.
- condition: It is the check which you want to add to return the error.
- error_message_1, error_message_2: These are the messages shown to user when there is an error.
- HTTP_Code_1, HTTP_Code_2: These are the HTTP status codes which we want to display to user along with error message.
Example: In this example, we are handling errors through two status codes, i.e., 200 for success, and 404 for error. The code 200 with message is displayed if roll number exist in students list, while the code 404 with message is displayed if roll number does not exist in students list.
Python3
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Student(BaseModel):
name: str
roll_number: int
students = {
1: Student(name="Abhishek", roll_number=1),
2: Student(name="Ishita", roll_number=2),
3: Student(name="Vinayak", roll_number=3),
}
@app.get("/items/{roll_number}")
def query_student_by_roll_number(roll_number: int) -> Student:
if roll_number not in students:
raise HTTPException(status_code=404, detail=f"Student with {roll_number=} does not exist.")
else:
raise HTTPException(status_code=200, detail=f"Student details are as follows: {students[roll_number]}")
Output: On calling the roll number 2 which exists in the student list, it displays an error message as follows:

On calling the roll number 4 which doesn't exist in the student list, it displays an error message as follows:

Built-In Exception Handlers in FastAPI
The built-in exception handler in FastAPI is using HTTP exception, which is normal Python exception with some additional data. In this method, we will see how we can handle error in FastAPI using built-in exception handlers.
Syntax: def function_name() -> Item:
if condition:
raise HTTPException(status_code=HTTP_Code, detail=f"error_message")
Here,
- function_name: It is the function which you want to call while testing.
- condition: It is the check which you want to add to return the error.
- error_message: It is the message shown to user when there is an error.
- HTTP_Code: It is the HTTP status code which we want to display to user along with error message.
Example: In this example, we are checking if the roll number of a student exists in the list of students, then that student value is returned else an error message is displayed.
Python3
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Student(BaseModel):
name: str
roll_number: int
students = {
1: Student(name="Abhishek", roll_number=1),
2: Student(name="Ishita", roll_number=2),
3: Student(name="Vinayak", roll_number=3),
}
@app.get("/items/{roll_number}")
def query_student_by_roll_number(roll_number: int) -> Student:
if roll_number not in students:
raise HTTPException(status_code=404, detail=f"Student with {roll_number=} does not exist.")
return students[roll_number]
Output: On calling the roll number 4 which doesn't exist in the student list, it displays an error message as follows:

Custom Exception Handlers in FastAPI
One of the crucial library in Python which handles exceptions in Starlette. It is also used to raise the custom exceptions in FastAPI. In this method, we will see how we can handle errors using custom exception handlers.
Syntax:
class UnicornException(Exception):
def __init__(self, value: str):
self.value = value
#Create a custom exception
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(status_code=404, content={"message": f"error_message"}, )
async def function_name(roll_number: int):
if condition:
raise UnicornException(value=condition_value)
Here,
- function_name: It is the function which you want to call while testing.
- condition: It is the check which you want to add to return the error.
- error_message: It is the message shown to user when there is an error.
- condition_value: It is the value on which condition needs to be checked.
Example: In this example, we are checking if the roll number of a student exists in the list of students, then that student value is returned else an error message is displayed.
Python3
from fastapi import FastAPI, Request
from pydantic import BaseModel
from fastapi.responses import JSONResponse
app = FastAPI()
class UnicornException(Exception):
def __init__(self, value: str):
self.value = value
class Student(BaseModel):
name: str
roll_number: int
students = {
1: Student(name="Abhishek", roll_number=1),
2: Student(name="Ishita", roll_number=2),
3: Student(name="Vinayak", roll_number=3),
}
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=404,
content={"message": f"Student with particular roll number does not exist."},
)
@app.get("/items/{roll_number}")
async def read_unicorn(roll_number: int):
if roll_number not in students:
raise UnicornException(value=roll_number)
return students[roll_number]
Output:
On calling the roll number 4 which doesn't exist in the student list, it displays an error message as follows:

Middleware in FastAPI
A function in FastAPI that works with each request before it is processed is known as middleware. In this method, we will see how we can handle errors in FastAPI using middleware.
Syntax: app.add_middleware(GZipMiddleware)
async def function_name():
if condition:
return (f"error_message")
Here,
- function_name: It is the function which you want to call while testing.
- condition: It is the check which you want to add to return the error.
- error_message: It is the message shown to user when there is an error.
Example: In this example, we are checking if the roll number of a student exists in the list of students, then that student value is returned else an error message is displayed.
Python3
from fastapi import FastAPI, Request
from pydantic import BaseModel
from fastapi.middleware.gzip import GZipMiddleware
app = FastAPI()
app.add_middleware(GZipMiddleware)
class Student(BaseModel):
name: str
roll_number: int
students = {
1: Student(name="Abhishek", roll_number=1),
2: Student(name="Ishita", roll_number=2),
3: Student(name="Vinayak", roll_number=3),
}
@app.get("/items/{roll_number}")
async def query_student_by_roll_number(roll_number: int):
if roll_number not in students:
return (f"Student with {roll_number=} does not exist.")
return students[roll_number]
Output:
On calling the roll number 4 which doesn't exist in the student list, it displays an error message as follows:

Logging in FastAPI
The crucial set of functions, such as debug, catch are provided by the logging in Python. In this method, we will see how we can handle errors in FastAPI using logging.
Syntax: logger = logging.getLogger(__name__)
async def function_name():
try:
if condition:
return (f"error_message")
return students[roll_number]
except Exception as e:
logger.exception(e)
raise HTTPException(status_code=500, detail="Internal server error")
Here,
- function_name: It is the function which you want to call while testing.
- condition: It is the check which you want to add to return the error.
- error_message: It is the message shown to user when there is an error.
Example: In this example, we are checking if the roll number of a student exists in the list of students, then that student value is returned else an error message is displayed.
Python3
from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel
import logging
app = FastAPI()
logger = logging.getLogger(__name__)
class Student(BaseModel):
name: str
roll_number: int
students = {
1: Student(name="Abhishek", roll_number=1),
2: Student(name="Ishita", roll_number=2),
3: Student(name="Vinayak", roll_number=3),
}
@app.get("/items/{roll_number}")
async def query_student_by_roll_number(roll_number: int):
try:
if roll_number not in students:
return (f"Student with {roll_number=} does not exist.")
return students[roll_number]
except Exception as e:
logger.exception(e)
raise HTTPException(status_code=500, detail="Internal server error")
Output:
On calling the roll number 4 which doesn't exist in the student list, it displays an error message as follows:

Conclusion:
It is not in our hands to stop the user from doing a certain action which can raise an error, but what is in our hands is to handle those errors so that user can get to know that they have done something wrong. The numerous methods defined in this article will help you to handle certain errors in FastAPI.
Similar Reads
Error Handling in Hyperledger Fabric
Error handling refers to the response and recovery procedures from the error conditions present in the software application. The clarity of the error messages and the options provided to users for fixing the issue determine the quality of such processes. Error handling comprises of anticipation, det
6 min read
Operating System Error Handling
An operating system is considered a medium between the computer systems and its users. After the booting process, the Operating System takes over and manages all of its applications on a device. The operating system is a key part of the framework software application in an electronic device. Since t
7 min read
Error Handling in Operating System
An operating system is defined as an interface between the computer system and its users. Once the operating system is loaded into the computer system through the boot program it is responsible for managing all the applications on the device. The operating system is a significant component of the sy
8 min read
FastAPI in Containers - Docker
FastAPI is also an open-source Starlette-ASGI (Asynchronous Server Gateway Interface) micro-web framework written in Python used to create RESTful APIs. Docker is a set of platform-as-a-service (PaaS) products that use OS-level virtualization to deliver software in packages called containers. Your p
4 min read
FastAPI - Using GraphQL
FastAPI and GraphQL have become prominent players in the realm of API development, each bringing its unique set of advantages to the table. GraphQL, initially created by Facebook, distinguishes itself with its efficiency and flexibility in data retrieval. In contrast to traditional REST APIs, GraphQ
5 min read
FastAPI - Type Hints
The readability and maintainability of your codebase can be greatly improved by comprehending and utilizing type hints. Developers can identify potential bugs early in the development process and produce more dependable and effective applications by clearly defining the expected data types. In this
3 min read
Handle Memory Error in Python
One common issue that developers may encounter, especially when working with loops, is a memory error. In this article, we will explore what a memory error is, delve into three common reasons behind memory errors in Python for loops, and discuss approaches to solve them. What is a Memory Error?A mem
3 min read
FastAPI - FastAPI Event Handlers
A Python framework that is used for building APIs is called FastAPI. There are some circumstances when the user needs to identify a certain event that happened in the API. This can be done using event handlers in FastAPI. In this article, we will study the various event handlers available in FastAPI
3 min read
Return an Image in FastAPI
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. Returning an image is a common requirement in web development, and FastAPI makes it straightforward to do. another famous framework for doing the same is Flask, which is also Python-based. In this article, we
4 min read
FastAPI - Pydantic
In this article, we will discuss FastAPI and Pydantic by using an example. So, let's get started. FastAPI and Pydantic are two potent tools within the Python ecosystem, highly acclaimed for their roles in crafting resilient and efficient web APIs. This article will guide you through the process of e
7 min read