This article demonstrates how to install and run FastAPI on an unmanaged server. FastAPI is a Python-based web framework for building APIs (Application Programming Interfaces).
Because FastAPI is asynchronous, it requires the Asynchronous Server Gateway Interface (ASGI) instead of the Web Server Gateway Interface (WSGI). Because our managed hosting solutions use Passenger and WSGI to manage Python applications, you can only install and run FastAPI on an unmanaged hosting account.
To install FastAPI, you first create a virtual environment for Python. After you activate the virtual environment, you can use the pip installer to install FastAPI.
To do this, follow these steps:
apt install curl python3.8-venv
As a regular (non-root) user, type the following commands:
cd ~ python3 -m venv fastapi-test cd fastapi-test source bin/activate
The virtual environment is now created and activated. To update pip, type the following command:
pip install --upgrade pip
To install FastAPI, type the following commands:
pip install fastapi pip install "uvicorn[standard]"
FastAPI is now installed. To determine which version is installed, type the following command:
pip show fastapi
FastAPI is now installed, and you can create and configure FastAPI applications. The following example shows how to do this.
from typing import Union 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: Union[str, None] = None): return {"item_id": item_id, "q": q}
To start the development web server, type the following command::
uvicorn main:app --reload
In another terminal window, type the following command:
curl localhost:8000/items/5?q=my_query
You should see the following JSON response:
{"item_id":5,"q":"my_query"}
You now have a basic, functioning web API created using FastAPI.
For more information about FastAPI, please visit https://fastapi.tiangolo.com.
Subscribe to receive weekly cutting edge tips, strategies, and news you need to grow your web business.
No charge. Unsubscribe anytime.
Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.
We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.