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.
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 pyenv
for managing Python versions:
curl https://pyenv.run | bash
Add pyenv
to 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 pip
and the necessary FastAPI
dependencies:
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.
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 FastAPI
and Uvicorn:
pip install fastapi uvicorn
Create a main.py
file and open it in a text editor:
touch main.py
Inside the main.py
file, 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.py
file and close the text editor.
Start the FastAPI
development 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