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
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
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
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
PYGLET â Loading a Image
In this article we will see how we can load a image resource in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as
2 min read
Returning Image/Media Data with Spring MVC
Spring MVC is a popular framework to build web applications in Java. One of the common requirements in web development is handling image or media data such as pictures, videos, or audio files. In Spring MVC, handling image or media data involves configuring a controller to receive requests for speci
3 min read
React Native Image Component
In this article, We are going to see how to add images in react-native. For this, we are going to use the Image component. It is used to add images in react-native. Syntax: <Image source={}/>Props in Image: accessible: If its value is true, then it indicates that the image is an accessibility
3 min read
Generate Images With OpenAI in Python
We are currently living in the age of AI. Images to automate processes including image generation for logos, advertisements, stock images, etc. So here we will use OpenAI to generate Images with Python [ChatGPT API]. There are numerous uses of the DALL - E model and today we will be discussing how o
8 min read
Python PIL | Image.draft() method
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
Wand - Convert image format
Image Format describes how an image data is being stored. Different image formats have different merits and demerits. There are around 7 most common image formats which are used in different cases. For example - The advantage of JPEG format is that it supports 24-bit color with up to 16 million colo
1 min read
Servlet - Display Image
The FileInputStream class is used to read the picture, and the ServletOutputStream class is used to write the image content as a response. We used the BufferedInputStream and BufferedOutputStream classes to improve performance. We must utilize the image/jpeg content type. Within the C:\Images direct
2 min read