NewSchokr 13 is here. A whole new UI, seven locations, snapshots and more. Read more →

How to deploy a FastAPI app with uvicorn

Run FastAPI on Schokr with uvicorn bound to 0.0.0.0 and your allocated port, from a startup command or a Python entry file.

Updated · 1 min read

To deploy FastAPI on Schokr, run it with uvicorn on host 0.0.0.0 and the port from your server's Network section. uvicorn's default of 127.0.0.1:8000 will not be reachable.

1. The app

main.py:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def root():
    return {"status": "ok"}

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

requirements.txt:

fastapi==0.115.0
uvicorn[standard]==0.30.6

2. Start uvicorn

From a startup command

uvicorn main:app --host 0.0.0.0 --port 25571

Replace 25571 with your port. Do not use --reload in production; it watches files and uses extra memory.

From a Python file

If your template runs a Python file instead of a custom command, start uvicorn from code. Create run.py:

import os
import uvicorn

if __name__ == "__main__":
    port = int(os.environ.get("APP_PORT", "8000"))
    uvicorn.run("main:app", host="0.0.0.0", port=port, proxy_headers=True)

Then set run.py as the file to run in your server's Startup settings.

3. Deploy on Schokr

  1. Create a server with the Python template in the console. 256 to 512 MB of memory is enough for most APIs.
  2. Upload main.py, run.py (if used) and requirements.txt with the file manager.
  3. Set the startup command or file, depending on what the template offers.
  4. Start the server. Look for Uvicorn running on http://0.0.0.0:<port> in the console.
  5. Open http://<server-address>:<port>/docs to see the interactive API docs.

Multiple workers

uvicorn can run several worker processes:

uvicorn main:app --host 0.0.0.0 --port 25571 --workers 2

Each worker loads your whole app, so memory use roughly multiplies. One worker handles a lot of async traffic; add workers only if CPU-bound work is slowing you down and you have memory to spare.

Background tasks and startup work

  • Use FastAPI's BackgroundTasks for small jobs after a response.
  • Use the lifespan handler to open database connections at startup.
  • For scheduled or long-running jobs, see background workers and scheduled jobs.

Calling the API from a browser

If a frontend on another domain calls your API, add CORS middleware:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://your-frontend.example"],
    allow_methods=["*"],
    allow_headers=["*"],
)

See CORS basics.

Troubleshooting

  • Error loading ASGI app. Could not import module "main": the file name or working directory does not match. See module not found.
  • address already in use: see port errors.