How to run fastapi app on multiple ports?

by lindsey.homenick , in category: Third Party Scripts , 16 days ago

How to run fastapi app on multiple ports?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 15 days ago

@lindsey.homenick 

To run a FastAPI app on multiple ports, you can use the uvicorn server with the --port option to specify multiple ports. Here's how you can do it:

  1. Install uvicorn if you haven't already:
1
pip install uvicorn


  1. Create a FastAPI app and save it in a file, for example app.py:
1
2
3
4
5
6
7
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}


  1. Run the FastAPI app on multiple ports using uvicorn:
1
uvicorn app:app --port 8000 --port 8001


This will start the FastAPI app on both ports 8000 and 8001 simultaneously. You can then access the app using http://localhost:8000 and http://localhost:8001.