Generic APIPath Parameters
Generic API~ 1 min read

Path Parameters

Introduction

This section will guide you through creating robust and well-defined API endpoints using Flama. We'll start with fundamental concepts like handling parameters and request data, move into data validation, and then cover more advanced features like pagination and modularizing your application.

Path Parameters

Path parameters are variable segments in the URL path. Flama allows you to define these in your route's path string and access them as arguments in your view function.

In Flama, you define path parameters using curly braces in the path string of a route. The name inside the braces must correspond to a parameter in your view function's signature.

Defining a route with path parameters

You can use either the @app.route() decorator or the app.add_route() method:

import flamafrom flama import Flama
app = Flama()
@app.route("/items/{item_id}")async def read_item(item_id: int): return {"item_id": item_id}
# Alternatively, using app.add_route:async def read_another_item(item_id: int, name: str): return {"item_id": item_id, "name": name} app.add_route("/other_items/{item_id}/by_name/{name}", read_another_item)
if __name__ == "__main__": flama.run(flama_app=app)

In the example above:

  • /items/{item_id}: The path contains one parameter, item_id.
  • async def read_item(item_id: int): The view function read_item expects an argument named item_id. Flama will automatically validate that the path segment corresponding to item_id can be converted to an int. If the conversion fails (e.g., /items/foo), Flama will return a 400 Bad Request error.

Flama uses type hints for automatic data validation and conversion of path parameters. The ValidatePathParamsComponent is responsible for this validation. The supported primitive types for path parameters are defined in flama.types.http.PARAMETERS_TYPES.