English 中文(简体)
FastAPI - Hello World
  • 时间:2024-09-17

FastAPI - Hello World


Previous Page Next Page  

Getting Started

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


from fastapi import FastAPI
app = FastAPI()

This app object is the main point of interaction of the apppcation with the cpent browser. The uvicorn server uses this object to psten to cpent’s request.

The next step is to create path operation. Path is a URL which when visited by the cpent 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, pst, 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 apppcation 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 apppcation startup.
INFO: Apppcation startup complete.

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

FastAPI Hello Advertisements