FastAPI Project: Installation and Setup Guide
FastAPI offers a reliable and practical framework for creating Python APIs, and the project setup and installation procedures are simple. FastAPI is a fantastic option for creating high-quality web APIs because of its robust features and fantastic performance.
Dependencies installation
The complete directions for installing Python 3.7 and the required dependencies for FastAPI can be found here:
Update the system's package manager and install essential packages:
apt updateapt install -y software-properties-common curl
Install
pyenvfor managing Python versions:
curl https://pyenv.run | bash
Add
pyenvto the system's environment:
echo 'export PATH="$HOME/.pyenv/bin:$PATH"' >> ~/.bashrcecho 'eval "$(pyenv init --path)"' >> ~/.bashrcecho 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrcsource ~/.bashrc
Install build dependencies for Python:
apt install -y build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev \libsqlite3-dev llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
Install Python 3.7 using
pyenv:
pyenv install 3.7.12pyenv global 3.7.12
Verify that Python 3.7 is installed:
python --version
Install
pipand the necessaryFastAPIdependencies:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.pypython get-pip.pypip install fastapi pydantic uvicorn
With these steps, you'll have Python 3.7 installed using pyenv and the necessary dependencies for FastAPI.
Please note that the installation steps assume a Linux-based environment. If you're using a different operating system, the steps may vary. Additionally, ensure you have the necessary privileges to perform system-level installations.
Step-by-step guide
Here's a guide for setting up a basic FastAPI project.
Create a new project directory:
mkdir fastapi-projectcd fastapi-project
Set up a virtual environment:
python3 -m venv venvsource venv/bin/activate
Install
FastAPIand Uvicorn:
pip install fastapi uvicorn
Create a
main.pyfile and open it in a text editor:
touch main.py
Inside the
main.pyfile, copy and paste the following code as a starting point:
from fastapi import FastAPIapp = FastAPI()@app.get("/")def read_root():return {"Hello": "World"}@app.get("/items/{item_id}")def read_item(item_id: int, q: str = None):return {"item_id": item_id, "q": q}
Save the
main.pyfile and close the text editor.Start the
FastAPIdevelopment server:
uvicorn main:app --reload
Open a web browser and navigate to http://localhost:8000 to see the "Hello World" message.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
You now have a basic FastAPI project set up with a couple of examples of routes. You can continue building your API by adding more routes, models, and logic per your project requirements.
Free Resources