Wednesday, 2 February 2022

FastAPI: status_code: Specify response status code

By setting 'status_code' parameter to the decorator method (@app.get(), @app.post(), @app.put(), @app.delete()), we can explicilty set the return code.

 

Example

@app.post("/emps", status_code=201)
def createEmployee(emp: Employee):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = emp
    return {"id" : newId, "name" : emp.name, "age": emp.age, "country": emp.country}

 

Find the below working application.

 

statusCode.py

from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from enum import Enum

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.post("/emps", status_code=201)
def createEmployee(emp: Employee):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = emp
    return {"id" : newId, "name" : emp.name, "age": emp.age, "country": emp.country}

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

 

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

 

Open the url ‘http://localhost:8000/docs’ in browser and experiment with the api ‘POST /emps’.

 


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment