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.

Creating the Basic HTML Document Structure

Let's start by setting up the basic HTML structure in the "app/templates/index.html" file. This will serve as the foundation for our web application.

  1. DOCTYPE Declaration and HTML Tag: Begin by declaring the document type and opening the HTML tag with the language attribute set to English.

    <!DOCTYPE html>
    <html lang="en">

    The <!DOCTYPE html> declaration defines the document type and version of HTML. The <html lang="en"> tag specifies the language of the document, which is important for accessibility and SEO.

  2. Head Element: Next, add the head element, which contains metadata about the document.

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>AI Short Story Generator</title>
        <link rel="stylesheet" href="{{ url_for('static', path='style.css') }}">
    </head>
    • The <meta charset="UTF-8"> tag sets the character encoding for the document, ensuring it can display all characters correctly.
    • The <meta name="viewport" content="width=device-width, initial-scale=1.0"> tag ensures the page is responsive and displays correctly on all devices.
    • The <title> tag sets the title of the page, which appears in the browser tab.
    • The <link> tag links the CSS file using FastAPI's Jinja2 url_for function, ensuring the styles are applied to the page.
  3. Body Element: Finally, add the body element, which will contain the content of the page.

    <body>
    </body>

    The <body> tag is where all the visible content of the page will go. For now, it's empty, but we'll be adding more elements soon.

Adding Tab Navigation

Now, let's create a tab navigation system within the body element. This will allow users to switch between different sections of the application.

Tabs Container: Start by creating a div with the class "tabs" to hold the navigation buttons.

<div class="tabs">
    <button class="tab-button" onclick="openTab('generate')">Generate Story</button>
    <button class="tab-button" onclick="openTab('history')">View History</button>
</div>
  • The <div class="tabs"> element acts as a container for the tab buttons.
  • Each <button> element represents a tab. The onclick attribute calls the openTab function with the respective tab ID, allowing users to switch between tabs.

Next, we'll update the "generate" div with form elements and layout to allow users to input story prompts and generate stories.

Generate Tab Content: Create a div with the ID "generate" to hold the content for the "Generate Story" tab.

<div id="generate" class="tab-content">
    <div class="container">
        <h1>AI Short Story Generator</h1>
        <input type="text" id="prompt" placeholder="Enter your story theme...">
        <label for="tone">Tone (Optional):</label>
        <select id="tone">
            <option value="">None</option>
            <option value="Mysterious">Mysterious</option>
            <option value="Adventurous">Adventurous</option>
            <option value="Humorous">Humorous</option>
            <option value="Inspirational">Inspirational</option>
        </select>
        <button id="generate-button" onclick="generateStory()">Generate Story</button>
        <p id="loading-message" style="display: none;">Generating story... Please wait.</p>
        <div id="story-container"></div>
    </div>
</div>
  • The <h1> element serves as the title for the tab.
  • The <input> element allows users to enter a story theme.
  • The <select> element provides a dropdown menu for selecting the tone of the story.
  • The <button> element triggers the generateStory function to generate a story.
  • The <p> element displays a loading message while the story is being generated.
  • The <div id="story-container"> is where the generated story will be displayed.

Now, let's modify the "history" div to include elements for viewing past stories.

History Tab Content: Create a div with the ID "history" to hold the content for the "View History" tab.

<div id="history" class="tab-content" style="display:none;">
    <div class="container">
        <h1>Story History</h1>
        <button onclick="fetchHistory()">Load Previous Stories</button>
        <div id="history-container"></div>
    </div>
</div>
  • The <h1> element serves as the title for the tab.
  • The <button> element triggers the fetchHistory function to load previous stories.
  • The <div id="history-container"> is where the history of stories will be displayed.
  • The style="display:none;" attribute ensures this tab is initially hidden.
Finalizing the HTML Structure and Summary

Finally, let's add the script tag at the end of the body to include the JavaScript file and ensure everything is well organized.

  1. Script Tag: Add the script tag to include the JavaScript file.

    <script src="{{ url_for('static', path='script.js') }}"></script>

    This script tag links the JavaScript file using FastAPI's Jinja2 url_for function, ensuring the scripts are correctly loaded.

  2. Verify Structure: Ensure all elements are correctly nested and organized within the HTML structure. This is crucial for the application to function properly.

In summary, we've set up the basic HTML structure for our AI Short Story Generator application. This includes creating a tab navigation system, developing content for the "Generate Story" and "View History" tabs, and linking the necessary CSS and JavaScript files. In the upcoming practice exercises, you'll have the opportunity to reinforce these concepts and ensure your HTML structure is ready for further development.

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