Return an Image in FastAPI
Last Updated :
24 Apr, 2025
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 will focus on creating API for images using FastAPI.
Return an Image in FastAPI
Installation of the necessary Library
For creating API using FastAPI we need fastAPI, also for running the server we also need a uvicorn. so before starting our API coding part, we need to the installation of fastAPI and uvicorn. We can install them by running the below command:
pip install fastapi
pip install uvicorn
To return an image in FastAPI, we will first need to have an image file that we want to serve. Let's assume we have an image file named "gfglogo.jpg" that we want to return as a response to the client who is requesting the API. Now let's start creating API using FastAPI
Importing FastAPI and Additional Libraries
First of all create one folder with the name you want, eg GFGAPI, inside that folder create a file with the name 'main.py'. add the image you want to return as a response in that folder eg, "gfglogo.jpg". The code in main.py file is the to import FastAPI and Additional Libraries which we need to create API as required.
Python3
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pathlib import Path
Creating a FastAPI App
Now to use fastAPI we need to create it's app, it's very simpe as we just need to call FastAPI().
Python3
Defining a Route to Serve the Image
We define a route '/get_image' using the @app.get decorator. This route will handle GET requests. In this step we need to make route to our app, as when any API request will come to our app first of all it will try to match with the url we mentioned inside app.get(), here get because client want the image in response so, client will send the get request.
We define the path to the image file. You should replace "gfglogo.jpg" with the actual path to your image file, if your file is inside the folder where the main.py file then simply write "filename.jpg".
We then check if the file exists using image_path.is_file(). If the image file is not found, we return an error message, otherwise we return the image as a FileResponse. FastAPI will automatically handle the response headers and content type for us, making it easy to serve images
Python3
@app.get("/get_image")
async def get_image():
image_path = Path("gfglogo.jpg")
if not image_path.is_file():
return {"error": "Image not found on the server"}
return FileResponse(image_path)
Code Implemenataion
In this example, we've created a FastAPI app and defined a route at "/get_image" that returns the "gfglogo.jpg" file as a response using FileResponse. If the file doesn't exist, it returns an error message.
Here you found that async keyword is used because reading a file (in this case, an image file) is typically an I/O-bound operation that can benefit from asynchronous handling. By marking the route as async, FastAPI can take advantage of asynchronous I/O operations, making the server more efficient and responsive when serving the file such as image file.
Python3
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pathlib import Path
app = FastAPI()
@app.get("/get_image")
async def get_image():
image_path = Path("gfglogo.jpg")
if not image_path.is_file():
return {"error": "Image not found on the server"}
return FileResponse(image_path)
Deployement of the Project
You can run the FastAPI app using a web server such as uvicorn:
uvicorn your_app_name:app --reload
Replace 'your_app_name' with the name of the file we given, here we had given file name as 'main.py' so use main.
uvicorn main:app --reload
Now, when you access 'http://localhost:8000/get_image' or 'http://127.0.0.1:8000/get_image' in your web browser or make a GET request to that URL using a tool like postman, the FastAPI app will return the image as a response.
Output
VS code editor terminal code & output
output of API in browserYou can also test this api by Postman by just sending GET request on "http://127.0.0.1:8000/get_image". This is all about how we can return an image using FatsAPI. By following these steps, you can create a FastAPI route that serves images to clients. This is a simplified example to do this.
Similar Reads
FastAPI - Header Parameters
FastAPI is the fastest-growing Python API development framework, It is easy to lightweight, and user-friendly and It is based on standard Python-type hints, which makes it easier to use and understand. FastAPI supports header parameters, these are used to validate and process incoming API calls. In
4 min read
Returning an Image or a File with Spring
In web development, it is common for servers to send various types of content to clients, including static and dynamic data, images, and files. The Spring Framework provides powerful tools to handle these requirements efficiently, allowing developers to return images and files directly from endpoint
3 min read
FastAPI - Response Model
FastAPI has garnered substantial recognition in the realm of web development, providing a swift and effective framework for constructing APIs using the renowned programming language, Python. The creation of APIs holds paramount importance in web development. A notable feature of FastAPI is its Respo
5 min read
Introduction to FastAPI And Installation
Introduction to FastAPIFastAPI is a modern, fast (as the name suggests), and highly performant Python web framework used for building APIs. It is built on top of standard Python-type hints and is powered by asynchronous programming using Python's "asyncio". FastAPI is known for its speed, simplicity
4 min read
Displaying a Single Image in PyTorch
Displaying images is a fundamental task in data visualization, especially when working with machine learning frameworks like PyTorch. This article will guide you through the process of displaying a single image using PyTorch, covering various methods and best practices.Table of ContentUnderstanding
3 min read
FastAPI - Introduction
Developers are continuously on the lookout for technologies that allow them to rapidly and efficiently construct sophisticated APIs and online applications. FastAPI, a relatively new addition to the Python web framework landscape, has quickly garnered traction due to its speed, simplicity, and devel
5 min read
Python PIL | Image.getdata()
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files,
2 min read
FastAPI - Query Parameters
In this article, we will learn about FastAPI Query Parameters, what are query parameters, what they do in FastAPI, and how to use them. Additionally, we will see examples of query parameters for best practices. What is FastAPI - Query Parameters?Query parameters stand as a formidable asset in bolste
6 min read
Python - Image() function in Wand
In this specific article we will learn how to read our image through Python wand module. To read image in Wand we use Image() function. To manipulate an image first of all we need to read image in Python. Parameters : Parameter Input Type Description image Image make exact copy of image blob bytes o
2 min read
FastAPI - Cookie Parameters
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 on how to use Cookie in FastAPI. What are Cookies?Cookies are pieces of data stored on the client browser by the server when the
4 min read