Last modified: Mar 25, 2025 By Alexander Williams
How to Install FastAPI in Python
FastAPI is a modern Python framework for building APIs. It is fast and easy to use. This guide will show you how to install FastAPI step by step.
Prerequisites
Before installing FastAPI, ensure you have Python 3.7 or higher. You can check your Python version using python --version
.
If you don't have Python installed, download it from the official website. Also, ensure pip is up to date by running pip install --upgrade pip
.
Install FastAPI
To install FastAPI, open your terminal or command prompt. Run the following command:
pip install fastapi
This will install the latest version of FastAPI. If you encounter a ModuleNotFoundError, check our guide on how to solve ModuleNotFoundError.
Install Uvicorn
FastAPI requires an ASGI server like Uvicorn to run. Install Uvicorn using pip:
pip install uvicorn
Uvicorn will handle the server part of your FastAPI application.
Create a Simple FastAPI App
Now, let's create a simple FastAPI application. Create a new file named main.py
and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
This code creates a basic API with one endpoint. The endpoint returns a JSON response.
Run the FastAPI App
To run the app, use Uvicorn. Execute the following command in your terminal:
uvicorn main:app --reload
The --reload
flag enables auto-reload for development. You should see output like this:
INFO: Uvicorn running on http://127.0.0.1:8000
Test the API
Open your browser and go to http://127.0.0.1:8000. You should see the JSON response:
{"message": "Hello, FastAPI!"}
You can also test the API using tools like Postman or curl.
Add More Endpoints
Let's add another endpoint to our API. Update main.py
with the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
This adds a new endpoint that accepts an item_id
as a path parameter.
Run and Test the New Endpoint
Restart the server if it's not auto-reloading. Then, visit http://127.0.0.1:8000/items/42.
You should see the response:
{"item_id": 42}
Conclusion
You have successfully installed FastAPI and created a simple API. FastAPI is powerful and easy to use. It is perfect for building APIs quickly.
For more advanced features, check the official FastAPI documentation. Happy coding!