This is the 8th day of my participation in the August More Text Challenge. For details, see:August is more challenging

background

Like the query parameters, the path parameters need to be qualified.

Path

In general, we use name: STR =’phyger’ to specify the type and default value of the Path parameter, but for advanced metadata of the Path parameter, we need to use the Path object provided by the FastApi.

The path parameter is usually required, so even if you specify the default parameter, it is still required.

The title of the path parameter

from fastapi import Path
@app.get('/path/{name}')
async def pth(name:str=Path(. ,title='path name')) :
    return {'path_name':name}
Copy the code

Specifies the format of the path parameter

The numerical validation

Is greater than2: gt =2Less than2: lt =2Greater than or equal to2: ge =2Less than or equal to2: le =2
Copy the code
from fastapi import Path
@app.get('/path/{name}')
async def pth(* ,name:int=Path(. ,title='path name',ge=2),q:str) :
    return {'path_name':name}
Copy the code

Sequence of path parameters

What if we have two URIs in our business model, one where the path parameters are fixed and the other where the path parameters are variables?

Assume that the views in the current service are as follows:

@app.get('/path/{name}')
async def pth(name:str=Path(. ,title='path name')) :
    return {'path_name':name}   

@app.get('/path/default')
async def f1() :
    return {'msg':'I am default path.'}
Copy the code

When we request /path/default, we get {‘ MSG ‘:’I am default path.’}.

Test it out:

What’s going on here? It’s not what I expected.

For /path/default, /path/{name} already intercepts all requests that match /path/ XXX. We only need to adjust the order of the two to be fixed before and changed after (the fixed path parameter is first, the changed path parameter is second).

Modified code

@app.get('/path/default')
async def f1() :
    return {'msg':'I am default path.'}


@app.get('/path/{name}')
async def pth(name:str=Path(. ,title='path name')) :
    return {'path_name':name}
Copy the code

Test again:

As you can see, /path/default has successfully intercepted and returned the correct result.

Test the non-fixed parameter function again:

As you can see, the other functions of our non-fixed path parameter are fine.

Thank you for reading, and don’t forget to follow, like, comment, and forward four times!