Created
December 12, 2021 05:41
-
-
Save raghavmri/929532239762f1c87bf513d63e9f809b to your computer and use it in GitHub Desktop.
A simple REST API using Python and FastAPI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import uvicorn # pip install uvicorn | |
from fastapi import FastAPI # pip install fastapi | |
from typing import Optional | |
# Create the FastAPI application | |
app = FastAPI() | |
# A simple example of a GET request | |
@app.get("/") | |
def read_root(): | |
return "Hello World!" | |
# A simple example of a GET request with a path parameter | |
@app.get("/items/{item_id}") | |
def read_item(item_id: int, q: Optional[str] = None): | |
return {"item_id": item_id, "q": q} | |
# A simple example of a POST request | |
@app.post("/items/") | |
def create_item(): | |
return { | |
"item_id": "created_item_id", | |
"q": "created_item_q", | |
} | |
# Run the server | |
if __name__ == "__main__": | |
uvicorn.run("main:app", | |
reload=True, # Reload the server when code changes | |
host="127.0.0.1", # Listen on localhost | |
port=5000, # Listen on port 5000 | |
log_level="info" # Log level | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment