FastAPI API Integration for Image Generation Service

Introduction to FastAPI API Integration

Welcome to the fifth lesson of our course on building an image generation service with FastAPI! In our previous lessons, we've built several key components of our application: the PromptManager for formatting user inputs, the ImageManager for storing and processing images, the ImageGeneratorService for connecting to Google's Gemini API, and most recently, the ImageGeneratorRouter, which handles input validation and response formatting.

Now it's time to bring everything together by creating the FastAPI application that will expose our functionality through HTTP endpoints. This is the final piece of our backend architecture that will allow users to interact with our image generation service through a web interface.

Our FastAPI API will have three main routes:

  1. A route to serve the main HTML page
  2. A route to handle image generation requests
  3. A route to retrieve all previously generated images

By the end of this lesson, you'll have a complete FastAPI API that integrates with the router we built previously, providing a clean interface for clients to generate and retrieve images.

Setting Up the FastAPI Application

Let's start by creating our FastAPI application. We'll set up the basic structure in our app/main.py file:

Python
import os
from fastapi import FastAPI, Request, HTTPException
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from routers.image_generator_router import ImageGeneratorRouter
import uvicorn

app = FastAPI(title="Image Generator API")

# Get the directory of the current script
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# Set up templates
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))

# Set up static files
app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "static")), name="static")

# Create router instance
image_generator_router = ImageGeneratorRouter()

We create a FastAPI application instance by calling FastAPI() with a title for our API. We determine the base directory of the current script and set up Jinja2Templates to handle our HTML templates, passing the directory where our templates are located.

We also mount a static files directory to serve static assets like CSS, JavaScript, and images.

Finally, we create an instance of our ImageGeneratorRouter. This router handles the business logic for our API endpoints.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal