Query parameters are a set of parameters attached to the end of a url. Query parameters go after the ? in a URL, separated by & characters.
For the uri http://localhost:8080/?name=sailu&gender=f, name is mapped to ‘sailu’ and ‘gender’ is mapped to f.
Example
@app.get("/emps/by-name")
def emByName(name: str):
if name == None:
return {"message" : "no input provided"}
for empId in emps:
if emps[empId]["name"] == name:
return emps[empId]
return {"message" : "Not found"}
Above snippet maps the query parameter name to the argument name.
Find the below working application.
main.py
from fastapi import FastAPI, Path
from typing import Optional
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", gt = 0, lt = 3)):
if(empId in emps):
return emps[empId]
else:
raise Exception("Employee not exist with given id " + str(empId))
@app.get("/emps/by-name")
def emByName(name: str):
if name == None:
return {"message" : "no input provided"}
for empId in emps:
if emps[empId]["name"] == name:
return emps[empId]
return {"message" : "Not found"}
Run the application by executing the command ‘uvicorn main:app --reload'.
Open the url ‘http://127.0.0.1:8000/docs’ and work with the api /emps/by-name.
Previous Next Home
No comments:
Post a Comment