FastAPI Hello World: Your First API in Minutes

Create, run, and test your first FastAPI application with this step-by-step guide.

Beginner 10 min Getting-Started 4 steps

Overview

You're new to FastAPI and want to create your first API endpoint to understand the basics.

What You'll Learn:

  • How to install FastAPI and Uvicorn
  • How to write a minimal FastAPI application
  • How to run the development server
  • How to test your API and view auto-generated documentation
1

Install FastAPI and Uvicorn

Estimated: 2 min

First, you need to install FastAPI and an ASGI server. Uvicorn is a popular choice for development. The `fastapi[all]` command installs FastAPI along with all its optional dependencies, including Uvicorn.

terminal
pip install "fastapi[all]"

This command installs FastAPI and all necessary dependencies for a complete development experience.

2

Create Your First API Endpoint

Estimated: 3 min

Create a file named `main.py`. In this file, you'll import FastAPI, create an app instance, and define a path operation (a route) that returns a JSON response.

info

FastAPI automatically converts the dictionary returned by `read_root()` into a JSON response.

tip

The function name `read_root` can be anything you like; FastAPI uses the decorator to associate it with the path.

main.py
from fastapi import FastAPI

# Create an instance of the FastAPI class
app = FastAPI()

# Define a path operation for the root URL
@app.get("/")
def read_root():
    return {"message": "Hello World"}

We import FastAPI, create an app instance, and use the `@app.get("/")` decorator to tell FastAPI that the function `read_root()` should handle requests to the root URL (`/`).

3

Run the Development Server

Estimated: 2 min

Now, run the Uvicorn server to serve your FastAPI application. Open your terminal in the same directory where you created `main.py`.

terminal
uvicorn main:app --reload

The `main:app` part tells Uvicorn to look for an object named `app` inside the `main.py` file. The `--reload` flag makes the server restart automatically after you change the code.

4

Test Your API and Explore Docs

Estimated: 3 min

With your server running, you can now interact with your new API. FastAPI provides interactive documentation automatically.