Building an Image Conversion and Serving API with FastAPI
Introduction: In this blog post, we will explore how to create a powerful FastAPI application that serves images and allows image conversion from base64-encoded data. By following this step-by-step guide, you will be able to set up a functional image API with FastAPI. We’ll cover both the image conversion function and an additional API endpoint to showcase the capabilities of FastAPI.
Prerequisites: Before you start, make sure you have the following prerequisites installed:
Python
FastAPI
uvicorn
HTTPie (optional, for testing the API)
Step 1: Set up the FastAPI Application Let’s start by setting up a FastAPI application and importing the required modules.
# main.py
import os
import uuid
import base64
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
app = FastAPI()
Step 2: Define the Image Conversion Function
We’ll create an image conversion function Image_Converter
that takes a base64-encoded image, decodes it, and saves it as a JPG file. Additionally, the function will return the URL of the converted image.
# main.py
...
async def Image_Converter(Hax_Value):
random_name = str(uuid.uuid4())
decodeit = open(f"Server/static/{random_name}.jpg", 'wb')
decodeit.write(base64.b64decode(Hax_Value))
decodeit.close()
img_path = "http://localhost:8000/images?id=Server%2Fstatic%2F" + str(random_name) + ".jpg"
return img_path
Step 3: Set Up the Image Serving Endpoint
Now, let’s define an endpoint /images
that will receive the image ID and return the corresponding image file.
# main.py
...
@app.post("/convert_image", tags=["IMAGE"])
async def convert_image(Hax_Value: str):
img_path = await Image_Converter(Hax_Value)
return {"converted_image_url": img_path}
Step 4: Create an Additional API Endpoint
For demonstration purposes, let’s create an additional endpoint /convert_image
that will receive a base64-encoded image and use the Image_Converter
function to convert and return the URL of the converted image.
# main.py
...
@app.post("/convert_image", tags=["IMAGE"])
async def convert_image(Hax_Value: str):
img_path = await Image_Converter(Hax_Value)
return {"converted_image_url": img_path}
Step 5: Mount the Static Files Directory
Now, let’s mount the directory containing the static files (images) to the /Static
endpoint so that they can be served by the FastAPI application.
# main.py
...
IMAGEDIR = os.getcwd()
app.mount("/Static", StaticFiles(directory="Server"), name="Static")
Step 6: Run the FastAPI Application
Finally, we can run the FastAPI application using uvicorn.
uvicorn main:app --reload
Conclusion:
Congratulations! You have successfully built an Image Conversion and Serving API with FastAPI. The /convert_image
endpoint allows you to convert base64-encoded images to JPG files and return the URL of the converted image. The /images
endpoint serves the converted images stored in the /Static
directory.
This example demonstrates the power and simplicity of FastAPI, making it an excellent choice for building APIs with Python. With FastAPI, you can easily create APIs for various applications, including image processing, machine learning, data analysis, and more. Feel free to customize and extend this example to suit your specific requirements and explore more features offered by FastAPI. Happy coding!
Subscribe to my newsletter
Read articles from Saurabh Chodvadiya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Saurabh Chodvadiya
Saurabh Chodvadiya
Python Developer | Transforming Ideas into Code 🐍 | Open-source Enthusiast | Lifelong Learner 📚 Upwork link:-https://www.upwork.com/freelancers/~012f5a97ee90286e33