FastAPI - Hello World



Getting Started

The first step in creating a FastAPI app is to declare the application object of FastAPI class.

from fastapi import FastAPI
app = FastAPI()

This app object is the main point of interaction of the application with the client browser. The uvicorn server uses this object to listen to client’s request.

The next step is to create path operation. Path is a URL which when visited by the client invokes visits a mapped URL to one of the HTTP methods, an associated function is to be executed. We need to bind a view function to a URL and the corresponding HTTP method. For example, the index() function corresponds to ‘/’ path with ‘get’ operation.

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

The function returns a JSON response, however, it can return dict, list, str, int, etc. It can also return Pydantic models.

Save the following code as main.py

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
   return {"message": "Hello World"}

Start the uvicorn server by mentioning the file in which the FastAPI application object is instantiated.

uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.

Open the browser and visit http://localhost:/8000. You will see the JSON response in the browser window.

FastAPI Hello
Advertisements