Build code HTTP Server FastAPI
Here is a sample code for building an HTTP Server using FastAPI in Python:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
In this code, we first import the FastAPI module and create an instance of the FastAPI class. We then define two endpoints using the @app.get
decorator. The first endpoint is for the root URL ("/") and returns a simple JSON response. The second endpoint is for a URL that includes a variable item_id, and also accepts an optional query parameter q.
To run this code, you can save it in a Python file (e.g. main.py
) and then use the following command in the terminal:
uvicorn main:app --reload
This will start the HTTP server on http://localhost:8000/
. You can then visit http://localhost:8000/items/42
(or any other item_id value) to see the response from the read_item
endpoint.

原文地址: http://www.cveoy.top/t/topic/0zv 著作权归作者所有。请勿转载和采集!