DEV Community

Zhao Xinhao
Zhao Xinhao

Posted on • Edited on

Hello World service in Python

A "Hello World" service does one thing: it responds to request with the text "Hello, World!".

FastAPI is modern,fast,and provides automatic API documentation.
Here's a guide to creating a Hello World service with FastAPI:

1.Installation
First,install the required packages:

bash
pip install fastapi uvicorn

Unicorn is a super-fast server for Python that runs web applications.
FasAPI to create the application, and Uvicorn to start it and handle incoming web requests.

2.Basic Hello World Service
Create a file main.py:
simplest:
python

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def hello_world():
    return "helloworld"
Enter fullscreen mode Exit fullscreen mode

improve:

from fastapi import FastAPI

# Create FastAPI instance
app = FastAPI(
    title = "Hello World API",
    description = "A simply Hello World service",
    version = "1.0.0"
)

# Define a simple GET endpoint
@app.get("/")
async def hello_world():
    return {"message": "Hello, World!"}
Enter fullscreen mode Exit fullscreen mode

3.Running the Service
Using uvicorn directly

bash
uvicorn main:app --reload or
uvicorn main:app --reload --host 0.0.0.0 --port 8000

Means:
"Uvicorn,please run the FastAPI app named app from the main.py file.Watch for code changes and reload automatically.Let any device on the network connect to it, and serve it on port 8000."

4.Testing the Service
Once running, we can access:
http://localhost:8000 or http://127.0.0.1:8000
And you will get the {"message":"Hello, World!"} in brower.
It's done!If you want to keep going, here are next steps:

5.Add a New Endpoint
Try creating a new "greet" endpoint that takes a name as input:

python

# Define a GET endpoint about greet
@app.get("/greet/{name}")
def greet(name: str):
    return {"message": f"Hello, {name}!"}
Enter fullscreen mode Exit fullscreen mode

Test it at: http://localhost:8000/greet/Alice.

6.Try a POST Request
Accept data(like a username)from the user:

python

from pydantic import BaseModel

class User(BaseModel):
    username: str

# Define a Post endpoint about login
@app.post("/login")
def login(user: User):
    return {"message": f"Welcome, {user.username}!"}
Enter fullscreen mode Exit fullscreen mode

Using FastAPI's /docs page,go to http://localhost:8000/docs, find POST /login,click"Try it out",enter the json,and hit "Execute".Then you send the data to server.

Top comments (0)