How to Build a REST API With FastAPI: Step-by-Step Tutorial
TL;DR: To build a REST API with FastAPI, install the library via pip and create a Python file containing route definitions using decorators. Run the application with the Uvicorn server command to start serving requests at a local URL.
FastAPI has become a favorite among developers for creating high-performance, modern web APIs in Python. Its speed is comparable to Go and NodeJS, while its development speed is boosted by automatic documentation and data validation. This guide walks you through the essential steps to get your first API up and running quickly.
If you want to dig deeper, check out our guide on **Telehealth Expands Into Preventive Care: What to Know** (5.
Step 1: Installation and Setup
First, ensure you have Python 3.8 or higher installed on your machine. Open your terminal or command prompt and install FastAPI along with Uvicorn, which is the ASGI server used to run the application. Execute the following command: pip install fastapi uvicorn. It is highly recommended to create a virtual environment before installing packages to keep your project dependencies isolated. Use the command python -m venv venv to create the environment, then activate it using source venv/bin/activate on Linux or macOS, or venv\Scripts\activate on Windows.
Step 2: Create the Application Instance
Create a new file named main.py in your project directory. Inside this file, import the FastAPI class and create an instance of it. This instance is your main application object that will handle all incoming requests. Add the following code: from fastapi import FastAPI followed by app = FastAPI(). This simple line sets up the core structure of your API.
Step 3: Define Your First Endpoint
Now, let’s create a simple endpoint that returns a greeting message. Use the @app.get() decorator to specify the HTTP method and the URL path. For example, add @app.get("/") above a function definition. The function should be named read_root and return a dictionary, which FastAPI automatically converts to JSON. The code should look like this: def read_root(): return {"message": "Hello World"}. This endpoint will respond to GET requests made to the root URL of your server.
Step 4: Add Path Parameters
Next, create an endpoint that accepts dynamic data. Define a new route using @app.get("/items/{item_id}"). Define the function parameter item_id with a type hint of int. FastAPI will automatically validate that the incoming data is an integer. If a user passes a string like “abc”, the API will return a 422 validation error without any extra code from you. This feature saves significant time on input validation.
Step 5: Run the Server
With your code ready, start the development server by running the command uvicorn main:app --reload in your terminal. The --reload flag automatically restarts the server when you save changes to your code, which is incredibly useful during development. Once the server starts, you can access your API at http://127.0.0.1:8000. FastAPI also generates interactive documentation at http://127.0.0.1:8000/docs, allowing you to test endpoints directly in the browser.
Step 6: Deploying Your API
When you are ready to deploy, consider using a production-grade server like Gunicorn with Uvicorn workers. You can create a gunicorn configuration or simply run gunicorn main:app -w 4 -k uv
Leave a Reply