Wednesday 27 October 2021

FastAPI: Working with path parameters

Path parameters are used to bind segments of paths to method parameters.

 

Sample Syntax

/emps/by-id/{empId}

 

Examples

/emps/by-id/1 -> Gives the details of employee with id 1

/emps/by-id/2 -> Gives the details of employee with id 1

 

FastAPI snippet

@app.get("/emps/by-id/{empId}")
def empById(empId: int):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

 

In the above example, the value of the path parameter ‘empId’ will be passed to your function as the argument ‘empId’. As you see the above snippet, I defined the type of a path parameter to int.

 

Is specifying the type to a path parameter mandatory?

No, but specifying the type helps in various occasions. For example,

a.   it will give you editor support inside of your function, with error checks, completion, etc.

b.   It helps while validating the data. Since I mentioned empId is of type int, FastAPI will validate the type of data before processing and send proper error message on validation failures.

$curl -X 'GET' \

>   'http://127.0.0.1:8000/emps/by-id/aa' \

>   -H 'accept: application/json'

{"detail":[{"loc":["path","empId"],"msg":"value is not a valid integer","type":"type_error.integer"}]}

 

Example

@app.get("/emps/by-id/{empId}")
def empById(empId: int):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

 

main.py

from fastapi import FastAPI

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):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

 

Run main.py file by executing the command ‘’.

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

  Open the url ‘127.0.0.1:8000/emps/by-id/1’ to get the employee with id 1 details.

 

 

Open the url ‘http://127.0.0.1:8000/emps/by-id/2’ to get the employee with id 2 details.



 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment