English 中文(简体)
FastAPI - Path Parameters
  • 时间:2024-12-22

FastAPI - Path Parameters


Previous Page Next Page  

Modern web frameworks use routes or endpoints as a part of URL instead of file-based URLs. This helps the user to remember the apppcation URLs more effectively. In FastAPI, it is termed a path. A path or route is the part of the URL traipng after the first ‘/’.

For example, in the following URL,


http://localhost:8000/hello/TutorialsPoint

the path or the route would be


/hello/TutorialsPoint

In FastAPI, such a path string is given as a parameter to the operation decorator. The operation here refers to the HTTP verb used by the browser to send the data. These operations include GET, PUT, etc. The operation decorator (for example, @app.get("/")) is immediately followed by a function that is executed when the specified URL is visited. In the below example −


from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
   return {"message": "Hello World"}

Here, ("/") is the path, get is the operation, @app.get("/") is the path operation decorator, and the index() function just below it is termed as path operation function.

Any of the following HTTP verbs can be used as operations.

Sr.No. Method & Description
1

GET

Sends data in unencrypted form to the server. Most common method.

2

HEAD

Same as GET, but without the response body.

3

POST

Used to send HTML form data to the server. Data received by the POST method is not cached by the server.

4

PUT

Replaces all current representations of the target resource with the uploaded content.

5

DELETE

Removes all current representations of the target resource given by a URL.

The async keyword in the function’s definition tells FastAPI that it is to be run asynchronously i.e. without blocking the current thread of execution. However, a path operation function can be defined without the async prefix also.

This decorated function returns a JSON response. Although it can return almost any of Python’s objects, it will be automatically converted to JSON. Further in this tutorial, we shall see how such a function returns Pydantic model objects.

The URL’s endpoint or path can have one or more variable parameters. They can be accepted by using Python’s string formatting notation. In the above example URL http://localhost:8000/hello/TutorialsPoint, the last value may change in every cpent request. This variable parameter can be accepted in a variable as defined in the path and passed to the formal parameters defined in the function bound to the operation decorator.

Example

Add another path decorator with a variable parameter in the route, and bind hello() function to have name parameter. Modify the main.py as per the following.


import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
   return {"message": "Hello World"}
@app.get("/hello/{name}")
async def hello(name):
   return {"name": name}

Start the Uvicorn server and visit http://localhost:8000/hello/Tutorialspoint URL. The browser shows the following JSON response.


{"name":"Tutorialspoint"}

Change the variable path parameter to something else such as http://localhost:8000/hello/Python so that the browser shows −


{"name":"Python"}

Check OpenAPI docs

Now if we check the OpenAPI documentation by entering the URL as http://localhost:8000/docs, it will show two routes and their respective view functions. Cpck the try out button below /hello/{name} button and give Tutorialspoint as the value of the name parameter’s description and then cpck the Execute button.

FastAPI Path Parameters

It will then show the Curl command, the request URL and the details of server’s response with response body and response headers.

FastAPI Path Parameters

A route can have multiple parameters separated by "/" symbol.


from fastapi import FastAPI
app = FastAPI()
@app.get("/hello/{name}/{age}")
async def hello(name,age):
   return {"name": name, "age":age}

In this case, /hello is the route, followed by two parameters put in curly brackets. If the URL given in the browser’s address bar is http://localhost:8000/hello/Ravi/20, The data of Ravi and 20 will be assigned to variables name and age respectively. The browser displays the following JSON response −


{"name":"Ravi","age":"20"}

Path Parameters with Types

You can use Python’s type hints for the parameters of the function to be decorated. In this case, define name as str and age as int.


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

This will result in the browser displaying an HTTP error message in the JSON response if the types don’t match. Try entering http://localhost:8000/hello/20/Ravi as the URL. The browser’s response will be as follows −


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

The reason is obvious as age being integer, can’t accept a string value. This will also be reflected in the Swagger UI (OpenAPI) documentation.

FastAPI Path Parameters Advertisements