Hello! Let's continue our journey into building APIs with FastAPI.
In our last lesson, we successfully set up your development environment. You created a project directory, established a virtual environment, and installed FastAPI and Uvicorn. We even verified the setup with a minimal "Hello World" application to ensure everything was working.
Today, we'll dive deeper into that minimal application. Our goal is to create a minimal FastAPI application with a single GET endpoint and run it with Uvicorn, but this time with a full understanding of what each piece of code does. We will deconstruct the "Hello World" example, explore the key concepts of path operations, and solidify your understanding of how to run the application server.
1. Anatomy of a Minimal FastAPI App
Let's revisit the code from our main.py file. It's concise, but every line serves a distinct purpose.
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}
Since you're comfortable with Python decorators, the @app.get("/") syntax might already look familiar. It's the heart of how FastAPI connects a URL to your code. To get an authoritative breakdown of this structure, the official FastAPI documentation is the best place to turn.
Please read the following sections from the official FastAPI documentation. They provide a clear, step-by-step explanation of each component in our minimal application.
In the article, find the section titled 'Recap, step by step'. Read through 'Step 1' to 'Step 5'. This will walk you through the import, the app instance, the decorator, the function, and the return value.
As you've just read, we can summarize the structure into four main parts:
from fastapi import FastAPI: We import the necessary class from the library. ThisFastAPIclass provides all the core functionality.app = FastAPI(): We create an instance of theFastAPIclass. Thisappobject is the main point of interaction for creating all the parts of your API.@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/using aGEToperation.def read_root(): ...: This is the path operation function. It's a standard Python function that FastAPI calls whenever it receives a matching request. The value returned by this function is sent back to the client as the body of the HTTP response.
2. Path, Operation, and Function
Let's focus on the most critical part: the connection between the decorator and the function.
@app.get("/")
- Path: The path is the part of the URL that comes after the domain. In this case,
"/"refers to the root of your site (e.g.,http://127.0.0.1:8000/). If you were to use"/items/", the full URL would behttp://127.0.0.1:8000/items/. - Operation: The operation refers to the HTTP method.
getis used for reading data. FastAPI provides decorators for all standard HTTP methods, such as@app.post(),@app.put(), and@app.delete(), which we will use in later lessons.
def read_root(): return {"message": "Hello World"}
This function is executed when a GET request to / is received. Notice that it returns a standard Python dictionary. FastAPI automatically handles the conversion of this dictionary (and many other data types) into a JSON response. This is a powerful feature that simplifies development, as you don't need to manually serialize your data.
You'll also see that the function is defined with def. Given your experience with async/await, you'll be glad to know that FastAPI works seamlessly with both standard synchronous functions (def) and asynchronous ones (async def). We'll explore the implications of this choice in more detail later, but for simple, non-I/O-bound operations like this, a standard def is perfectly fine.
3. Running the Server with Uvicorn
In the previous lesson, you ran uvicorn main:app --reload to start the server. Now that you understand the components inside main.py, that command should make more sense.
uvicorn: The ASGI server program.main:app: This tells Uvicorn where to find the application instance. It follows the format<module_name>:<instance_name>. So, it looks in themain.pyfile (themainmodule) for the variable namedapp.--reload: This development-friendly flag tells Uvicorn to monitor your project files for changes and automatically restart the server when you save a file. This gives you a very fast feedback loop.
The following video provides a great demonstration of this process and introduces an alternative command you can also use.
Python FastAPI Tutorial (Part 1): Getting Started - Web App + REST API
Watch this clip from Corey Schafer. He explains how to run the development server and demonstrates the utility of the auto-reload feature.
Watch from 10:41 to 12:37. He uses the fastapi dev command, which is a convenient wrapper around the uvicorn command we've been using. Pay attention to how the server automatically restarts when he saves a code change.
Your Turn: Hands-On Practice
Let's put this knowledge into practice.
- Open your terminal in the project directory.
- Make sure your virtual environment is activated.
- Run the server:
uvicorn main:app --reload - Open your browser and navigate to
http://127.0.0.1:8000. You should see{"message":"Hello World"}. - Now, go back to your
main.pyfile in your code editor. - Change the return value of the
read_rootfunction to something different. For example:return {"status": "ok", "version": "1.0"}. - Save the file.
- Look at your terminal. You should see Uvicorn detect the change and restart the server.
- Go back to your browser and refresh the page at
http://127.0.0.1:8000. You will now see your new JSON response.
This simple exercise demonstrates the entire development cycle: writing code, running the server, and testing the result.
Conclusion
In this lesson, we moved from simply running code to understanding it. You've dissected a minimal FastAPI application and now have a clear mental model of how it works.
Here are the key takeaways:
- An endpoint in FastAPI is a combination of a path operation decorator (like
@app.get("/")) and a path operation function that handles the request. - FastAPI automatically converts Python data structures like dictionaries into JSON responses.
- The
uvicorn main:app --reloadcommand is your primary tool for running the server during development, providing a fast and efficient workflow with its auto-reloading capability.
You've now mastered the fundamental building block of any FastAPI application. With this foundation, we can start exploring more powerful features.
In the next lesson, we will look at one of FastAPI's most celebrated features: the automatic interactive API documentation (Swagger UI). You'll learn how to use this tool to test your endpoints directly in the browser, a skill that will dramatically accelerate your development and testing process.