Hello! Welcome back to our course on FastAPI.
In our last lesson, we dove into one of FastAPI's core architectural features: the distinction between async def and def route handlers. You learned that async def is for high-concurrency, non-blocking I/O, while def is for CPU-bound tasks or legacy blocking code, which FastAPI smartly runs in a thread pool.
Today, we move from theory to practice. We'll take all the foundational concepts—ASGI, the async model, and the structure of a path operation—and build our very first, running FastAPI application.
Learning Outcome: Define and run a minimal FastAPI application using uvicorn, comparing the workflow to Django's runserver.
This lesson is the "Hello, World!" moment of your FastAPI journey. We'll mirror the process you're familiar with from Django (django-admin startproject, python manage.py runserver) and see how FastAPI achieves the same result with a more direct and lightweight approach.
From Django's Structure to FastAPI's Simplicity
In Django, starting a project involves a formal ceremony: you run django-admin startproject to generate a directory structure, a manage.py script, and settings files. To get a single "Hello, World!" response, you typically need to create an app, define a view, and configure a URL pattern.
FastAPI streamlines this significantly. Let's see just how different the setup is.
Django vs FastAPI: Choosing the Right Python Web Framework
The article 'Django vs FastAPI' from Betterstack provides a side-by-side comparison of the setup process for both frameworks. This will give you a clear picture of the contrast in their initial workflows.
Read the section titled 'Setup and project structure'. Pay close attention to the code snippets for both Django and FastAPI. Notice the number of files and commands required for Django versus the single file needed for FastAPI.
As you saw, FastAPI requires much less boilerplate. Let's walk through the steps to create our own minimal application.
Step 1: Installation
First, you need two packages:
fastapi: The framework itself.uvicorn: An ASGI (Asynchronous Server Gateway Interface) server to run your application.
Think of uvicorn as the FastAPI equivalent of the development server that runs when you execute python manage.py runserver in Django. While Django's server is built-in for development, FastAPI relies on a separate, production-ready ASGI server like Uvicorn.
Open your terminal and install them:
pip install fastapi "uvicorn[standard]"
(Note: We use "uvicorn[standard]" to include extra dependencies that provide better performance and WebSocket support, which will be useful later.)
Step 2: Creating Your First FastAPI App
Now, create a single file named main.py. This file will contain your entire application for now.
Add the following code to main.py:
# main.py
from fastapi import FastAPI
# 1. Create an instance of the FastAPI class
app = FastAPI()
# 2. Define a path operation decorator
@app.get("/")
# 3. Define the path operation function
async def root():
# 4. Return the content
return {"message": "Hello, World"}
Let's break this down, drawing parallels to Django:
app = FastAPI(): This creates the main application object. It's the central point of your API. All your routes, middleware, and configurations will be attached to thisappinstance. This is conceptually similar to your project's rooturls.pyin Django, where everything comes together.@app.get("/"): This is a path operation decorator. It tells FastAPI that the function directly below it is responsible for handling requests that go to:- the path
/(the root URL). - using a
GETHTTP method.
This decorator elegantly combines what Django separates intourlpatterns(the path) and the logic within a view that might checkif request.method == 'GET'.
- the path
async def root():: This is your path operation function, the direct equivalent of a Django view function. We're usingasync defhere, as we learned in the last lesson. Since we're just returning a dictionary and not performing any blocking I/O, bothasync defanddefwould work, butasyncis the natural default in FastAPI.return {"message": "Hello, World"}: FastAPI automatically converts this Python dictionary into a JSON response with the appropriateContent-Type: application/jsonheader. This is a major convenience compared to Django, where you'd typically useJsonResponseto achieve the same result.
Step 3: Running the Server
With your main.py file saved, go back to your terminal (make sure you're in the same directory) and run the following command:
uvicorn main:app --reload
Let's dissect this command:
main: This refers to yourmain.pyfile (the Python module).app: This refers to theapp = FastAPI()object you created insidemain.py.--reload: This is a lifesaver for development. It tells Uvicorn to automatically restart the server whenever you save changes to your code, just like Django'srunserverdoes.
The video below gives a great walkthrough of these steps.
FastAPI Full Crash Course - Python’s Fastest Web Framework
The 'FastAPI Full Crash Course' video by NeuralNine provides a clear, practical demonstration of creating this minimal app and running it with Uvicorn.
Watch the segment from 09:55 to 13:02. The presenter will write the code we just discussed and run the uvicorn command. Notice the output in the terminal, which tells you where the server is running.
Once you run the command, you should see output indicating the server is running, usually on http://127.0.0.1:8000. Open that URL in your browser, and you will see your JSON response: {"message":"Hello, World"}.
Step 4: Discovering the Automatic API Docs
Here is where FastAPI truly shines and offers a massive advantage out of the box. Now, navigate to http://127.0.0.1:8000/docs in your browser.
You will see an interactive API documentation page (Swagger UI). This was generated automatically by FastAPI based on your code.
Django/DRF Analogy: This is similar to the browsable API provided by Django REST Framework, but it's built into FastAPI itself and requires zero configuration. It adheres to the OpenAPI standard, which is the industry norm for documenting REST APIs.
This interactive documentation allows you to see all your endpoints, their parameters, and even test them directly from the browser.
FastAPI Full Crash Course - Python’s Fastest Web Framework
Let's return to the 'FastAPI Full Crash Course' video to see a quick tour of this documentation interface.
Watch the short clip from 27:22 to 28:48. The presenter introduces the /docs endpoint and shows how you can use it to explore and test your API. This is a feature you will use constantly during development.
Conclusion
Congratulations! You have successfully built and launched your first FastAPI application. While simple, this exercise highlights the core differences in developer experience compared to Django.
Key Takeaways:
- Workflow: The FastAPI workflow is
install -> code -> run. It's more direct than Django'sstartproject -> startapp -> configure -> code -> runcycle for simple APIs. - Server: FastAPI uses an ASGI server like Uvicorn to run. The command
uvicorn main:app --reloadis your equivalent ofpython manage.py runserver. - Code Structure: A minimal app can exist in a single file. Path operations are defined concisely using decorators (
@app.get) right above the functions that handle them. - Automatic Docs: FastAPI provides free, interactive API documentation at the
/docsendpoint, a powerful tool for development and collaboration.
In our next lesson, we will build upon this foundation. We'll explore how FastAPI leverages Python's type hints not just to improve documentation, but to provide powerful, automatic request validation—a role that serializers handle in DRF.