How to Install FastAPI on Mac: A Practical Step-by-Step Guide
This guide shows how to install FastAPI on Mac with step-by-step instructions for setup, running, and troubleshooting your app.
You want to develop a FastAPI application on your Mac but aren’t sure where to begin. Setting up the environment correctly and understanding the steps can save time and avoid frustration.
This guide covers how to install FastAPI on Mac with a clear, practical step-by-step approach. You will learn how to prepare your Mac for FastAPI, create and run your first application, set it to start automatically, and troubleshoot common issues. Comparisons with other environments will help you choose the best setup for your needs.
Key takeaways
- Ensure Python 3.7 or higher is installed before starting.
- Use virtual environments to manage FastAPI dependencies cleanly.
- Run FastAPI apps with Uvicorn for optimal performance on Mac.
- Set up launch agents to run your app automatically at startup.
- Common issues include port conflicts and missing dependencies; troubleshooting tips are provided.
Before you start: prerequisites for installing FastAPI on Mac
To install FastAPI on your Mac smoothly, you need to prepare your environment and tools correctly. FastAPI requires Python version 3.7 or higher, so verifying your Python installation is the first step. Open the Terminal app and enter python3 --version. You should see an output like Python 3.9.1 or higher to proceed.
Next, check that the package manager pip is available by running pip3 --version. This command confirms pip is installed and ready to handle package installations needed for FastAPI.
Basic familiarity with terminal commands is essential since installation and running FastAPI involve command-line operations. If you are new to the terminal, learning commands like cd, ls, and python3 will help you follow the installation steps without confusion.
Using a virtual environment is highly recommended but optional. It isolates your FastAPI project dependencies from system-wide Python packages, reducing conflicts and easing maintenance. Virtual environments can be created using python3 -m venv env, and once activated, all package installations remain confined to this environment.
- Open Terminal and type python3 --version. You should see a Python version 3.7 or above.
- Type pip3 --version to verify pip is installed and responding.
- (Optional) Create a virtual environment with python3 -m venv env, then activate it using source env/bin/activate. Your terminal prompt will change, indicating the virtual environment is active.
System Python installations are sometimes outdated or used by macOS internally, which can cause permission or compatibility issues. Using virtual environments avoids these problems by keeping your FastAPI dependencies separate and controlled.
How to install FastAPI in Python on your Mac
Installing FastAPI on your Mac is straightforward using Python's package manager, pip. Alongside FastAPI, you need an ASGI server like Uvicorn to run your applications, as FastAPI itself is just a framework and doesn't handle serving your app.
- Open your Terminal application.
- Type pip install fastapi and press Enter. You should see output indicating that FastAPI and its dependencies are being downloaded and installed, ending with a message similar to "Successfully installed fastapi-".
- Next, install Uvicorn by typing pip install uvicorn and pressing Enter. The terminal will show progress messages and conclude with "Successfully installed uvicorn-", confirming the ASGI server is ready.
Uvicorn is necessary because FastAPI uses the ASGI specification to handle asynchronous server communications, and Uvicorn is a lightweight, efficient server that supports this. Without Uvicorn or a similar ASGI server, your FastAPI application cannot be run or tested.
Example output when installing FastAPI might look like this:
Collecting fastapi
Downloading fastapi-0.85.0-py3-none-any.whl (54 kB)
Installing collected packages: fastapi
Successfully installed fastapi-0.85.0
And for Uvicorn:
Collecting uvicorn
Downloading uvicorn-0.18.3-py3-none-any.whl (53 kB)
Installing collected packages: uvicorn
Successfully installed uvicorn-0.18.3
Once these installations complete without errors, FastAPI and Uvicorn are ready to use on your Mac.
How to setup FastAPI: creating your first application

- Create a new file named main.py in your project folder. This file will contain your FastAPI app code.
- Open main.py in a text editor and write the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello, FastAPI on Mac!"}
This code sets up a FastAPI instance named app and defines a basic GET route at the root path that returns a JSON message. - Save the file. The code components work as follows:
- from fastapi import FastAPI: imports the FastAPI class needed to create your application.
- app = FastAPI(): creates an instance of the FastAPI application.
- @app.get("/"): a decorator that declares an asynchronous GET endpoint at the root URL.
- async def read_root(): defines an asynchronous function to handle requests at this endpoint, demonstrating FastAPI’s support for async request processing.
- return {"message": "Hello, FastAPI on Mac!"}: sends a JSON response back to the client.
- Organize your files simply by keeping main.py in the root project directory for this minimal setup. For larger apps, you can create subfolders like routers or models to separate concerns but this is not required at this stage.
- After saving main.py, your minimal FastAPI app is ready to run and handle asynchronous HTTP GET requests at the root URL, returning a JSON message to confirm it works.
How to run FastAPI app on your Mac
Running your FastAPI application locally on your Mac involves using the Uvicorn server, which is designed to serve ASGI applications like FastAPI efficiently. The recommended approach during development is to include the --reload option, which enables automatic code reload upon file changes.
- Open your Terminal and navigate to your project directory containing the main.py file.
- Run the command uvicorn main:app --reload. This tells Uvicorn to look for the app instance inside the main.py file and enables hot reload.
- By default, Uvicorn serves on
127.0.0.1(localhost) at port8000. If you want to specify a different host or port, run uvicorn main:app --reload --host 0.0.0.0 --port 8080 to listen on all network interfaces at port 8080. - After running the command, you should see terminal output indicating Uvicorn has started, including the address and port where the app is available, for example: "Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)".
- Open your preferred web browser and navigate to the displayed URL (e.g.,
http://127.0.0.1:8000). You should see your FastAPI app's root response or the default route content. - To verify the app is working correctly, append
/docsto the URL (e.g.,http://127.0.0.1:8000/docs). This opens the automatically generated interactive API documentation, a clear indicator your app is running properly.
Using the --reload option is ideal for development but should be disabled in production to improve performance and security. Specifying --host 0.0.0.0 allows access from other devices on your network, which can be useful for testing on mobile or other computers.
How to run FastAPI application on startup
You can automate the launch of your FastAPI app on Mac startup by creating a launch agent using launchd. This method runs your app in the background each time you log in, ensuring continuous availability without manual start. Alternatively, tools like screen or tmux sessions can keep your app running persistently but need manual session management.
- Create a plist file named com.yourusername.fastapiapp.plist in
~/Library/LaunchAgents/. This file tells launchd how to start your FastAPI app. For example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.yourusername.fastapiapp</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/uvicorn</string>
<string>main:app</string>
<string>--host</string>
<string>127.0.0.1</string>
<string>--port</string>
<string>8000</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardOutPath</key>
<string>~/Library/Logs/fastapi_stdout.log</string>
<key>StandardErrorPath</key>
<string>~/Library/Logs/fastapi_stderr.log</string>
</dict>
</plist>This example assumesuvicornis installed at/usr/local/bin/uvicornand your app entry point ismain:app. - Load the launch agent by running in Terminal:
launchctl load ~/Library/LaunchAgents/com.yourusername.fastapiapp.plist
You should see no errors. Your FastAPI app will start immediately and on each login. - Verify the app is running by accessing
http://127.0.0.1:8000in your browser or checking the log files at~/Library/Logs/fastapi_stdout.logandfastapi_stderr.logfor output and errors. - If needed, unload the agent using:
launchctl unload ~/Library/LaunchAgents/com.yourusername.fastapiapp.plist
Alternatively, using screen or tmux allows you to run the FastAPI app in a detached terminal session that persists after logout. Start a session with screen -dmS fastapi uvicorn main:app --host 127.0.0.1 --port 8000 or similar. This requires manual session management but offers real-time access to the running process console.
Running your FastAPI app via launchd is the recommended approach for an automated, background startup on Mac, especially when combined with proper logging to diagnose startup or runtime issues.
How to use FastAPI effectively after installation
FastAPI offers powerful features to handle various types of request data. You can define path parameters to capture values directly from the URL, query parameters to filter or modify requests via URL queries, and request bodies to receive structured data as JSON or other formats.
For example, a path parameter looks like this in your route definition: @app.get("/items/{item_id}"). Query parameters are declared as function parameters with default values, and request bodies use Pydantic models for validation.
FastAPI automatically generates interactive API documentation that you can access by visiting /docs for Swagger UI or /redoc for ReDoc in your browser when your app is running. These interfaces let you test endpoints, view request schemas, and understand response formats without extra setup.
To maintain clarity as your project grows, organize your code by splitting routes into separate modules or routers. Use FastAPI’s APIRouter to group related endpoints, and keep models, services, and utility functions in dedicated folders. This structure improves maintainability and collaboration.
Here is a simple example of path and query parameters with a request body:
- Define a Pydantic model for the request body:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float - Create an endpoint using path and query parameters:
@app.put("/items/{item_id}")
async def update_item(item_id: int, q: str = None, item: Item = None):
return {"item_id": item_id, "q": q, "item": item} - Run your app and open http://localhost:8000/docs to see the auto-generated documentation with this endpoint ready for testing.
Using these tools and structuring your project clearly will help you leverage FastAPI's capabilities efficiently.
Troubleshooting common issues when installing or running FastAPI on Mac
When encountering problems with FastAPI on your Mac, start by verifying your Python version. A common error is:

"ModuleNotFoundError: No module named 'fastapi'"
This often means FastAPI was installed for a different Python version than the one running your app. Check your Python version with python3 --version and ensure you use pip3 linked to the same Python.
To fix pip errors like "pip command not found", install pip via sudo easy_install pip or use Python's ensurepip module.
Fixing port conflicts or server startup failures
If Uvicorn fails to start with an error like "OSError: [Errno 48] Address already in use", another process is using the port. Use lsof -i:8000 to identify the occupying process, then kill -9 [PID] to free the port.
After this, rerun your app and confirm it starts without errors and is accessible via http://127.0.0.1:8000.
Addressing virtual environment activation problems
If your virtual environment is not activating, you might see errors such as "command not found: activate". Ensure you run source /path/to/venv/bin/activate in your terminal session.
Once activated, your shell prompt typically changes to include the environment name, and running which python points to the virtual environment's Python binary.
- Check Python and pip versions with python3 --version and pip3 --version. You should see consistent versions aligned with your FastAPI installation.
- If you see module errors, reinstall FastAPI using pip3 install fastapi uvicorn inside the activated virtual environment.
- For port conflicts, run lsof -i:8000, note the PID, and terminate the process with kill -9 PID. Confirm the port is free by rerunning lsof -i:8000 to show no output.
- Activate your virtual environment by running source /path/to/your/venv/bin/activate. Your prompt should change, indicating activation.
- Start the FastAPI app with uvicorn main:app --reload. You should see server startup logs without error messages and confirmation that the app is running on http://127.0.0.1:8000.
Following these steps helps resolve common installation and runtime issues, ensuring a smooth FastAPI experience on your Mac.
- How to Install Jupyter Notebook on Mac: A Clear Step-by-Step Guide
- How to Install Miniconda on Mac: A Clear Step-by-Step Guide
- How to Install Anaconda on Mac: A Clear Step-by-Step Guide
Frequently asked questions
How to download fastapi?
You download FastAPI by installing it through Python's package manager, pip. Open your Mac Terminal and run pip install fastapi. This downloads and installs FastAPI and its dependencies directly from the Python Package Index (PyPI).
How to start fastapi app?
To start a FastAPI app, first create a Python script defining your FastAPI instance and endpoints. Then run the app using a server like Uvicorn with a command like uvicorn your_app_name:app --reload. This launches the development server and enables live code reloading for easier testing.
How to run the fastapi?
Running FastAPI requires an ASGI server such as Uvicorn. After installing Uvicorn, execute uvicorn app_name:app --host 127.0.0.1 --port 8000 in your Terminal, where app_name matches your Python file. This command starts the server, making your API accessible locally.
How to install FastAPI on Windows?
On Windows, open Command Prompt or PowerShell and ensure Python and pip are installed. Then run pip install fastapi followed by pip install uvicorn to install FastAPI and its recommended ASGI server. The process is similar to Mac but may require adjusting PATH variables.
What is the command to install FastAPI?
The command to install FastAPI is pip install fastapi. For full functionality, also install an ASGI server like Uvicorn using pip install uvicorn. Together, these enable you to develop and run FastAPI applications efficiently.
What this advice does not cover and who should look elsewhere
This article does not cover deploying FastAPI applications to production environments or advanced security configurations. If you need to deploy FastAPI in production, manage scaling, or implement complex authentication and authorization, you should consult dedicated resources focused on production deployment best practices.
For those working with other operating systems or requiring integration with large frameworks and infrastructure, specialized guides will provide more tailored instructions.
To build on your setup, the most useful next step is to familiarize yourself with FastAPI's extensive official documentation and experiment with adding routes, request validation, and asynchronous features. This hands-on approach will deepen your understanding and prepare you for more complex application development.