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:

  1. Log in to your server using SSH.

  2. Ubuntu users (as root): install curl and Python 3 virtual environment support:

apt install curl python3.8-venv

Note: Other Linux distributions may already have these packages installed. Consult your distribution’s documentation if not.

  1. As a regular (non-root) user, create and activate a virtual environment:

cd ~
python3 -m venv fastapi-test
cd fastapi-test
source bin/activate
  1. Update pip:

pip install --upgrade pip
  1. Install FastAPI and Uvicorn:

pip install fastapi
pip install "uvicorn[standard]"
  1. Verify the installation and version:

pip show fastapi

Running an example application
Now that FastAPI is installed, you can create a basic application:

  1. Create a file named main.py using a text editor.

  2. Copy the following code into main.py:

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}
  1. Start the development server:

uvicorn main:app --reload
  1. In another terminal, test the API using curl:

curl localhost:8000/items/5?q=my_query

Expected 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.

آیا این پاسخ به شما کمک کرد؟ 0 کاربر این را مفید یافتند (0 نظرات)

Powered by WHMCompleteSolution