0
0
FastAPIframework~5 mins

Accepting connections in FastAPI

Choose your learning style9 modes available
Introduction

Accepting connections means your FastAPI app listens for users' requests so it can respond to them.

When you want your web app to start and be ready to receive visitors.
When you deploy your FastAPI app on a server and want it to handle incoming requests.
When testing your API locally to see how it responds to calls.
When you want to open a specific port for your app to communicate over the internet.
Syntax
FastAPI
import uvicorn

if __name__ == "__main__":
    uvicorn.run("your_module:app", host="0.0.0.0", port=8000, reload=True)

Replace your_module:app with your Python file and FastAPI app instance name.

host="0.0.0.0" means listen on all network interfaces.

Examples
Listen only on your local machine (localhost) at port 8000.
FastAPI
uvicorn.run("main:app", host="127.0.0.1", port=8000)
Listen on all interfaces at port 8080 and auto-reload on code changes.
FastAPI
uvicorn.run("app:app", host="0.0.0.0", port=8080, reload=True)
Sample Program

This program creates a simple FastAPI app that says hello. It uses uvicorn.run to accept connections on localhost port 8000. The reload=True helps during development by restarting the server when code changes.

FastAPI
from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, FastAPI!"}

if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
OutputSuccess
Important Notes

Use host="0.0.0.0" to allow external devices to connect, but be careful with security.

The reload=True option is for development only; remove it in production.

Uvicorn is the server that runs your FastAPI app and handles connections.

Summary

Accepting connections means your app listens for requests on a network address and port.

Use uvicorn.run to start your FastAPI app and accept connections.

Choose the right host and port depending on where and how you want your app accessible.