Setting Up the HTML Structure and Project Layout with FastAPI

Introduction and Overview

Welcome to the first lesson of our course on building a Short Story Generation Web Application with FastAPI. In this lesson, we will focus on setting up the basic HTML structure for our application. This foundational step is crucial, as it lays the groundwork for the entire web application. By the end of this lesson, you will have a well-structured HTML document that serves as the backbone for our AI Short Story Generator. Let's dive in and start building!

App File Structure

Before we start building the HTML for our story generation interface, let's take a moment to understand how our FastAPI application is organized. A clear file structure helps us stay organized as our project grows in complexity.

Here's the structure we'll be working with:

app/

├── main.py                     # Entry point for running the FastAPI app

├── controllers/                # FastAPI route logic
│   └── story_generator_controller.py

├── services/                   # Core logic for story generation
│   └── story_generator_service.py

├── models/                     # Manages data and helper logic
│   ├── story_manager.py
│   └── prompt_manager.py

├── data/                       # Data template for story prompt
│   └── story_prompt_template.txt

├── static/                     # Frontend static files (CSS, JS, etc.)
│   ├── style.css
│   └── script.js

└── templates/                  # HTML templates rendered by FastAPI
    └── index.html

How FastAPI Serves Static Files and Templates

  • Templates: FastAPI uses the Jinja2Templates class to render HTML templates. Templates are stored in the templates/ directory.
  • Static Files: Static files such as CSS and JavaScript are served using FastAPI's StaticFiles class. These files are placed in the static/ directory and mounted in the FastAPI app.

In your FastAPI app, you might mount the static directory like this:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()
app.mount("/static", StaticFiles(directory="app/static"), name="static")

And in your HTML template, you can link to your stylesheet as follows:

<link rel="stylesheet" href="/static/style.css">

This tells FastAPI to serve the style.css file from the static folder.

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