Sunday, 6 February 2022

Can I pass a dictionary, list or any object while raising HttpException?

Yes, you can pass any value that can be converted to JSON as the parameter ‘detail’.

 

Example

@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id")):
    if(empId not in emps):
        raise HTTPException(
                status_code=404, 
                detail={"msg" : "Employee not found", "id" : empId}
            )
            
    return emps[empId]   

 

Find the below working application.

 

throwHttpException2.py
from fastapi import FastAPI, Path, HTTPException
from pydantic import BaseModel

app = FastAPI()

# model classes
class Employee(BaseModel):
    name: str
    age: int
    country: str

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32,
        "country": "India"
    },
    2 : {
        "name" : "Ram",
        "age": 33,
        "country": "China"
    },
    3 : {
        "name" : "Bomma",
        "age": 38,
        "country": "China"
    }
}

# Create home endpoint
@app.get("/")
def home():
    return {"name" : "Hello World app", "version": "2.0.0"}

# Employees REST APIs
@app.get("/emps")
def allEmployees():
    return emps
    
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id")):
    if(empId not in emps):
        raise HTTPException(
                status_code=404, 
                detail={"msg" : "Employee not found", "id" : empId}
            )
            
    return emps[empId]    

 

Open terminal and execute the command ‘uvicorn throwHttpException2:app --reload’.

$uvicorn throwHttpException2:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [63568] using statreload
INFO:     Started server process [63570]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

  Open the url ‘http://localhost:8000/docs’ in browser and execute the api 'GET /emps/by-id/{empId}' for empId 4, you will get http status code 404 and custom error object in the response body.

 


 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment