This is the second day of my participation in the August Text Challenge.More challenges in August

What is a path parameter

As the name implies, path parameters are the request parameters in the URL, such as querying information by ID.

Example: automatically capitalize the first letter

main.py

.@app.get('/format/{name}')
async def fmt(name) :
    new_name = name.title()
    return {'result':new_name}
...
Copy the code

Test after starting the service

Visit: http://127.0.0.1:8765/format/phyger

As you can see, the functionality has been implemented!

Existing problems

Visit: http://127.0.0.1:8765/format/123

Although the result is returned, we expect the format of the request parameters to be verified behind the scenes. Keep reading.

The default path argument types are all STR, so 123 has been converted to STR.

Formatted path parameters

When we’re working with numbers, we don’t want illegal types of data to be processed in the background.

The old code

.@app.get('/format1/{num}')
async def fmt1(num) :
    print(type(num))
    new_num = num+1
    return {'result':new_num}
...
Copy the code

Result of path parameter 123

Internal Server Error: 123 was treated as STR in the background, so there was an Error in the calculation.

The new code

@app.get('/format1/{num}')
async def fmt1(num:int) :
    print(type(num))
    new_num = num+1
    return {'result':new_num}
Copy the code

Result of path parameter 123

Success!

The difference between path parameters and query parameters

The path parameter is part of the owning URL, while the query parameter is used after the URL. Parameters for making the connection. We usually express the primary key part of a module data structure as a path parameter, and we usually express additional information about this object as a query parameter.

As the name implies, path parameters guide us to the object profile, while query parameters help us to find out more about the object.

More on query parameters will be covered in the next section.

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