Skip to content
OVEX TECH
Education & E-Learning

Build Your First FastAPI Web App and REST API

Build Your First FastAPI Web App and REST API

Build Your First FastAPI Web App and REST API

FastAPI is a modern, fast (high-performance) web framework for Python, built upon standard Python type hints. It’s rapidly gaining popularity due to its speed, built-in data validation, automatic API documentation, and excellent asynchronous support. This guide will walk you through setting up a basic FastAPI application, creating API endpoints that return JSON, and serving HTML responses, all while leveraging FastAPI’s powerful features.

What You’ll Learn

In this tutorial, you will learn how to:

  • Install FastAPI and its dependencies.
  • Create a basic FastAPI application instance.
  • Define API routes using decorators.
  • Return JSON data from API endpoints.
  • Run your FastAPI application using the command line.
  • Access and utilize FastAPI’s automatic API documentation (Swagger UI and ReDoc).
  • Serve HTML responses to web browsers.
  • Hide specific routes from the API documentation.

Prerequisites

  • Basic understanding of Python.
  • Python installed on your system (version 3.7+ recommended).
  • A code editor (like VS Code).
  • A terminal or command prompt.

Step-by-Step Guide

1. Set Up Your Project Directory

First, create a new directory for your project. You can use your preferred package manager or command-line tools. The example below uses uv, a modern Python package manager, but you can substitute pip commands if you prefer.

  1. Create a new directory for your project. For example, named fastapi_blog:

    Using uv:

    uv new fastapi_blog

    Using pip:

    mkdir fastapi_blog
    cd fastapi_blog
  2. Navigate into the newly created directory:

    Using uv:

    cd fastapi_blog

    Using pip:

    cd fastapi_blog

2. Install FastAPI

Install FastAPI along with uvicorn (an ASGI server) and the standard extras. This provides the core framework, a server to run your application, and the FastAPI CLI command.

  1. Install FastAPI and its standard extras:

    Using uv:

    uv add fastapi[standard]

    Using pip:

    pip install fastapi[standard]

    Note: The [standard] part installs FastAPI along with Uvicorn and the FastAPI CLI. Using quotes around the package name is recommended for compatibility across different terminals.

3. Create Your Basic FastAPI Application

Create a Python file (e.g., main.py) in your project directory and add the following code to set up your FastAPI application instance.

  1. Create a file named main.py in your project’s root directory.
  2. Add the following Python code:
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def home():
        return {"message": "Hello World"}

    Explanation:

    • from fastapi import FastAPI: Imports the necessary class from the FastAPI library.
    • app = FastAPI(): Creates an instance of the FastAPI application. This app object will be used to define all your API routes and settings.
    • @app.get("/"): This is a decorator that tells FastAPI that the function below it should handle GET requests to the root URL (/).
    • def home():: This defines the function that will be executed when a GET request is made to the root URL.
    • return {"message": "Hello World"}: The function returns a Python dictionary. FastAPI automatically converts this dictionary into a JSON response.

4. Run Your FastAPI Application

You can run your FastAPI application using the fastapi dev command, which provides auto-reloading and helpful debugging output, making it ideal for development.

  1. Open your terminal in the project directory.
  2. Run the application:

    Using uv (ensures the virtual environment is used):

    uv run main.py

    Using the FastAPI CLI (if not using uv or if your environment is set up):

    fastapi dev main.py

    Note: fastapi dev enables auto-reloading, so the server will restart automatically when you save changes to your code. For production, you would use fastapi run main.py.

5. Access Your API and Documentation

Once the server is running, you can access your application in a web browser.

  1. Open your web browser and navigate to http://127.0.0.1:8000. You should see the JSON response: {"message": "Hello World"}.
  2. Access the automatic API documentation:
    • Swagger UI: Navigate to http://127.0.0.1:8000/docs.
    • ReDoc: Navigate to http://127.0.0.1:8000/redoc.

    These interactive documentation pages are generated automatically from your code, showing available endpoints, their parameters, and expected responses. You can even test your endpoints directly from these pages.

6. Add Dummy Data and a JSON API Endpoint

Let’s add some dummy data and create an endpoint to retrieve it as a JSON array.

  1. Update your main.py file with the following code. Add the posts list at the top, before the app = FastAPI() line.
    from fastapi import FastAPI
    from fastapi.responses import HTMLResponse
    
    app = FastAPI()
    
    dummy_posts = [
        {
            "id": 1,
            "author": "John Doe",
            "title": "First Post",
            "content": "This is the content of the first post.",
            "date_posted": "2023-01-01"
        },
        {
            "id": 2,
            "author": "Jane Smith",
            "title": "Second Post",
            "content": "Content for the second post.",
            "date_posted": "2023-01-02"
        }
    ]
    
    @app.get("/")
    def home():
        return {"message": "Hello World"}
    
    @app.get("/api/posts")
    def get_posts():
        return dummy_posts
  2. Save the file. The development server should automatically reload.
  3. Access the new endpoint by navigating to http://127.0.0.1:8000/api/posts in your browser. You will see a JSON array of the dummy posts.
  4. Check the documentation at /docs or /redoc. You will now see the /api/posts endpoint listed.

7. Serve HTML Responses

To serve web pages to users, you need to return HTML. FastAPI allows you to return raw HTML strings.

  1. Modify the home route in main.py to return HTML:
    from fastapi import FastAPI
    from fastapi.responses import HTMLResponse
    
    app = FastAPI()
    
    dummy_posts = [
        {
            "id": 1,
            "author": "John Doe",
            "title": "First Post",
            "content": "This is the content of the first post.",
            "date_posted": "2023-01-01"
        },
        {
            "id": 2,
            "author": "Jane Smith",
            "title": "Second Post",
            "content": "Content for the second post.",
            "date_posted": "2023-01-02"
        }
    ]
    
    @app.get("/", response_class=HTMLResponse)
    def home():
        return "

    Welcome to the FastAPI Blog!

    " @app.get("/api/posts") def get_posts(): return dummy_posts

    Explanation:

    • from fastapi.responses import HTMLResponse: Imports the HTMLResponse class.
    • response_class=HTMLResponse: Added to the decorator, this tells FastAPI that the response should be treated as HTML.
    • The function now returns an HTML string.
  2. Save the file.
  3. Refresh http://127.0.0.1:8000 in your browser. You should now see the HTML heading Welcome to the FastAPI Blog!. You can verify this by viewing the page source.

8. Handle Multiple Routes for the Same Function and Hide from Docs

You can stack decorators to make multiple URLs point to the same function. You can also prevent certain routes (like HTML-serving ones) from appearing in the API documentation.

  1. Update your main.py file:
    from fastapi import FastAPI
    from fastapi.responses import HTMLResponse
    
    app = FastAPI()
    
    dummy_posts = [
        {
            "id": 1,
            "author": "John Doe",
            "title": "First Post",
            "content": "This is the content of the first post.",
            "date_posted": "2023-01-01"
        },
        {
            "id": 2,
            "author": "Jane Smith",
            "title": "Second Post",
            "content": "Content for the second post.",
            "date_posted": "2023-01-02"
        }
    ]
    
    @app.get("/", response_class=HTMLResponse, include_in_schema=False)
    def home():
        return "

    Welcome to the FastAPI Blog!

    " @app.get("/posts", response_class=HTMLResponse, include_in_schema=False) def posts_page(): # This function will return HTML for the /posts page # For now, we'll just return a simple message return "

    All Posts Page

    " @app.get("/api/posts") def get_posts(): return dummy_posts

    Explanation:

    • Stacking Decorators: To make both / and /posts serve HTML using the same logic, you would typically stack decorators. However, in this specific example, we’ve created two separate functions for clarity, but the concept of stacking applies. If you wanted both / and /posts to return the same Welcome to the FastAPI Blog! message, you would stack the decorators on a single function.
    • include_in_schema=False: This parameter is added to the route decorators. When set to False, the route will still function correctly in the browser but will be excluded from the automatic API documentation (Swagger UI and ReDoc). This helps keep your API documentation clean and focused on programmatic endpoints.
    • We’ve added a new route /posts that also returns HTML and is hidden from the schema.
  2. Save the file.
  3. Test the routes:
    • Navigate to http://127.0.0.1:8000 (should show Welcome to the FastAPI Blog!).
    • Navigate to http://127.0.0.1:8000/posts (should show All Posts Page).
    • Navigate to http://127.0.0.1:8000/api/posts (should show the JSON data).
  4. Check your documentation at /docs. You will notice that only the /api/posts endpoint is listed, while the HTML-serving routes are hidden.

Conclusion

Congratulations! You’ve successfully set up a basic FastAPI application, created API endpoints that return JSON, and served HTML responses. You’ve also learned how to leverage FastAPI’s automatic documentation and control its visibility. This is a solid foundation for building more complex web applications and APIs with FastAPI. In the next part of this series, we’ll explore using Jinja2 templates for more dynamic HTML generation.


Source: Python FastAPI Tutorial (Part 1): Getting Started – Web App + REST API (YouTube)

Leave a Reply

Your email address will not be published. Required fields are marked *

Written by

John Digweed

1,377 articles

Life-long learner.