Installing FastAPI on unmanaged servers
Installing FastAPI on unmanaged servers
Learn how to install and run FastAPI on an unmanaged server using the command line. FastAPI is a Python-based framework for building APIs (Application Programming Interfaces).
This article provides step-by-step instructions for installing and running FastAPI on an unmanaged server.
Important: FastAPI is asynchronous and requires the Asynchronous Server Gateway Interface (ASGI), not WSGI. Managed hosting environments using Passenger and WSGI cannot run FastAPI, so this setup is only for unmanaged hosting accounts.
Installing FastAPI
To install FastAPI, create a Python virtual environment, activate it, and then use pip to install FastAPI. Follow these steps:
- Log in to your server using SSH.
- Ubuntu users (as root): install
curland Python 3 virtual environment support:
apt install curl python3.8-venvNote: Other Linux distributions may already have these packages installed. Consult your distribution’s documentation if not.
- As a regular (non-root) user, create and activate a virtual environment:
cd ~python3 -m venv fastapi-testcd fastapi-testsource bin/activate- Update pip:
pip install --upgrade pip- Install FastAPI and Uvicorn:
pip install fastapipip install "uvicorn[standard]"- Verify the installation and version:
pip show fastapiRunning an example application
Now that FastAPI is installed, you can create a basic application:
- Create a file named
main.pyusing a text editor. - Copy the following code into
main.py:
from typing import Unionfrom 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: Union[str, None] = None): return {"item_id": item_id, "q": q}- Start the development server:
uvicorn main:app --reload- In another terminal, test the API using curl:
curl localhost:8000/items/5?q=my_queryExpected JSON response:
{"item_id":5,"q":"my_query"}You now have a basic working API built with FastAPI.
More information
For further details and documentation, visit FastAPI Official Site.