Skip to main content
In this article, you’ll learn how to set up a FastAPI project and run a simple web server. For a complete understanding, it’s recommended to review the FastAPI documentation and its introductory tutorial before you begin.

Installing FastAPI and Optional Dependencies

FastAPI can be easily installed via pip. It is recommended to install FastAPI with all its optional dependencies as they can be very useful when your project scales. Run the following command to install:
During the installation process, you’ll notice several additional packages being installed. For instance, you might see output similar to:
After installation, if you run pip freeze, you’ll see FastAPI along with its bundled optional dependencies, which may include GraphQL support, websockets, and more:
If you’re curious about the package code, you can find all installed packages within the lib folder of your virtual environment.

Creating a Basic FastAPI Application

After installing FastAPI, create a new Python file (e.g., main.py). In this file, import FastAPI and instantiate an application object named app following the documentation conventions:
The above code defines a basic path operation at the root URL (/) that returns a JSON response with a message saying “Hello World”. Remember to save your file after making changes. If your editor prompts you regarding auto-formatting (for instance, PEP8 compliance), it’s good practice to allow the change.

Running the Server

Once your FastAPI application is ready, you can start the server using Uvicorn. Since you’ve installed FastAPI with the [all] flag, Uvicorn is already available. Activate your virtual environment and run:
This command runs the server with the following parameters:
  • main: The name of your Python file (without the .py extension).
  • app: The FastAPI instance to be served.
  • --reload: Automatically reloads the server when code changes are detected.
You should see output similar to this:
Open your web browser and visit http://127.0.0.1:8000 to see a JSON response:
Additionally, your terminal will log incoming requests:
This confirms that your FastAPI application is functioning correctly.

Summary

In this lesson, you learned to:
  1. Install FastAPI along with optional dependencies using the [all] flag.
  2. Create a basic FastAPI application that provides a “Hello World” JSON response.
  3. Run the FastAPI server with Uvicorn and observe its output.
In the next section, we will explore each component of the code in more detail to understand the underlying functionality better.

Watch Video