Using the Path object, we can specify the description to a path variable.
Example
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id")):
if(empId in emps):
return emps[empId]
else:
raise Exception("Employee not exist with given id " + str(empId))
Find the below working application.
main.py
from fastapi import FastAPI, Path
app = FastAPI()
# employees information
emps = {
1 : {
"name" : "Krishna",
"age": 32
},
2 : {
"name" : "Ram",
"age": 33
}
}
# Create an endpoint
@app.get("/")
def home():
return {"name" : "Hello World app", "version": "2.0.0"}
# Employees REST APIs
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id")):
if(empId in emps):
return emps[empId]
else:
raise Exception("Employee not exist with given id " + str(empId))
Run the application by executing the command ‘uvicorn main:app --reload'
$uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [42574] using statreload
INFO: Started server process [42576]
INFO: Waiting for application startup.
INFO: Application startup complete.
Open the url
'http://127.0.0.1:8000/docs' and expand the REST endpoint '/emps/by-id/{empId}'.
You will see the description against empId parameter.
No comments:
Post a Comment