Back to Blog
Lesson 31 of the Python: Programming from Zero with Python course
PythonAugust 17, 20264 min read

Setting Up FastAPI: Build Your First Web Server

Learn how to set up FastAPI and Uvicorn to build high-performance web APIs. Follow this guide to initialize your project and launch a local development server.

PythonFastAPIBackendWeb DevelopmentUvicorn
Modern server rack with blue lighting in a secure data center environment.

Previously in this course, we explored the introduction to web frameworks, where we discussed the fundamental client-server architecture. Now that you understand the concepts behind endpoints and JSON responses, it’s time to move from theory to practice by building your own API.

In this lesson, we will install FastAPI and Uvicorn, create a minimal application, and launch a local development server.

Understanding the Stack: FastAPI and Uvicorn

FastAPI is a modern, high-performance web framework for building APIs with Python. It is designed to be easy to learn while providing performance comparable to Node.js or Go.

However, FastAPI itself is just a framework. To actually run the code and handle incoming network requests, we need an ASGI (Asynchronous Server Gateway Interface) server. This is where Uvicorn comes in. Think of it as the engine that powers your FastAPI application, listening for HTTP requests and translating them into Python code.

ComponentRole
FastAPIThe framework that defines your routes and data logic.
UvicornThe lightning-fast server that runs your FastAPI code.

Installing the Dependencies

Focused view of a computer screen displaying code and debug information.

Before writing code, ensure you have followed the guide on virtual environments. Working inside a virtual environment prevents dependency conflicts and keeps your project clean.

With your virtual environment activated, install the necessary packages using pip:

Bash
pip install fastapi "uvicorn[standard]"

Note: We use "uvicorn[standard]" to install extra dependencies that optimize performance, such as uvloop.

Creating Your First FastAPI App

Create a new file named main.py in your project folder. This will be the entry point for your API. We'll start with a "Hello World" style endpoint:

PYTHON
from fastapi import FastAPI

# Initialize the FastAPI application
app = FastAPI()

# Define a basic route
@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

In this snippet:

  1. We import FastAPI.
  2. We create an instance of the FastAPI class, which we call app.
  3. We use the @app.get("/") decorator to tell FastAPI that any request to the root URL (/) should trigger the read_root function.

Starting the Local Development Server

Now that the code is written, we need to run it using Uvicorn. Open your terminal in the same directory as main.py and run:

Bash
uvicorn main:app --reload

Here is what these arguments do:

  • main: Refers to the filename main.py.
  • app: Refers to the variable app we defined inside main.py.
  • --reload: This is a crucial development flag. It tells Uvicorn to restart the server automatically every time you save changes to your code.

Once running, you should see output in your terminal indicating that the server is active at http://127.0.0.1:8000. Open your browser and navigate to that address; you will see the JSON response: {"message": "Hello, FastAPI!"}.

Hands-on Exercise

Close-up of foam handle hand grippers for enhancing grip strength during workouts.

Modify your main.py to add a second endpoint. Create a function that responds to a request at /status and returns a dictionary like {"status": "online", "data_processed": 0}.

Restart your server (or let it reload if you used the --reload flag) and verify the response by visiting http://127.0.0.1:8000/status in your browser.

Common Pitfalls

  • Incorrect File/App Reference: If you name your file app.py but run uvicorn main:app, Uvicorn will fail because it cannot find the file. Ensure the string matches your filename.
  • Forgetting the Decorator: If you define a function but forget to add the @app.get("/") decorator, the route will not exist, and the API will return a 404 error when you try to access it.
  • Port Conflicts: If you see an "Address already in use" error, it means another process (or a previous instance of Uvicorn that didn't close properly) is already using port 8000. You can stop the process in your terminal with Ctrl+C.

Frequently Asked Questions

Q: Do I always need to use the --reload flag? A: No. Use it for local development only. When deploying to a production server, you should omit it for better performance and security.

Q: Why does my browser show a 404 error? A: Check that you have defined the endpoint correctly and that the server is actually running. Also, ensure you are visiting the correct path (e.g., / or /status).

Q: Is FastAPI only for APIs? A: While it is built specifically for APIs, you can use it to serve HTML templates or static files, though it is most powerful when serving JSON data.

Recap

Team members presenting a project in a modern office setting with a focus on collaboration.

In this lesson, we transitioned to web development by installing the FastAPI framework and the Uvicorn web server. We learned how to initialize an app, define a simple endpoint, and serve it locally. You now have the foundation to start building the API component of our data-processing project.

Up next: Defining API Endpoints

Similar Posts