Friday 4 February 2022

FastAPI: HTTPException: Return response with errors

Using ‘HTTPException’, you can return HTTP responses with errors to the client.

 

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="Item not found")
    return emps[empId]    

 

throwHttpException.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="Employee not found")
    return emps[empId]    

 

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

 

$uvicorn throwHttpException:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [25209] using statreload
INFO:     Started server process [25211]
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.

 


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment