Demystifying FastAPI Path Parameters

SAMPLe

Content:

  1. What is Path/End Point
  2. Operation Decorator
  3. Async keyword before operation decorator
  4. Multiple Parameter as end point
  5. Endpoint Parameter with Data Type

End Point/ Path

When you hit any api, the string trailing “/” is the path or the route of the url. For example

@app.get("/")

Here the end point is root that is

Where as for below

@app.get("/hello/mrabc")

The endpoint is /hello/mrabc

The end point can take any parameter also, we will see in trailing content.

Operation Decorator:

In fastapi, the operator decorator takes the parameter as the path/endpoint. The decorator is associated with some http operation like get/post/put/delete. Example:

@app.get("/")
async def root():
    return {"message": "Hello science"}

These decorator operation are immediately followed by a async method, which defines what operation need to be performed when these endpoint is called, like in above code the decorator operation is  “GET” so the async method is returning a json string to the calling environment.

Async keyword before operation decorator:

Aync keyword before the method which is immediately followed by decorator operation tells that this function can be independently run irrespective of any other thread running parallelly:

@app.get("/")
async def root():
    return {"message": "Hello science"}

Multiple Parameter as end point:

We can have multiple parameters also in the endpoint accepting multiple value like in below example:

@app.get("/hello/{firstname}/{lastname}")
async def hello_name(firstname, lastname):
    return {"name": firstname, "lastname": lastname}

Here we are taking two parameter and the same is passed to the binding method hello_name, the end point will be something like this where you can pass anything as firstname and lastname

The endpoint full path is: http://127.0.0.1:8000/hello/raj/mohan

Endpoint Parameter with Data Type:

We can also define the datatype of each parameter we pass from the endpoint in the binding method like below:

@app.get("/hello/{firstname}/{age}")
async def hello_name(firstname: str, age: int):
    return {"name": firstname, "age": age}

Here we define datatype for endpoint parameter firstname as str and age as int, lets call the api from web

Now lets tryout the same on swaggerUI, here I am passing name as “vikram” and age as “36”

In next post we will check query parameters.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *