Routing

Routing in Xyra is simple and intuitive. You can use decorators to map HTTP methods and URL paths to your handler functions.

Basic Routing

To create a route, use the decorator corresponding to the HTTP method you want to handle (e.g., @app.get, @app.post).

Python
from xyra import App, Request, Response

app = App()

@app.get("/")
def home(req: Request, res: Response):
    res.text("Hello, World!")

@app.post("/users")
async def create_user(req: Request, res: Response):
    # Assuming you get user data from the request body
    user_data = await req.json()
    res.status(201).json({"message": "User created", "data": user_data})

Route Parameters

You can define dynamic parts in your routes using curly braces (e.g., {user_id}). These parameters will be available in the req.params dictionary.

Python
@app.get("/users/{user_id}")
def get_user(req: Request, res: Response):
    user_id = req.params.get("user_id")
    # In a real app, you would fetch user data from a database
    res.json({"user_id": user_id, "name": f"User {user_id}"})

Query Parameters

Query parameters from the URL (e.g., ?q=xyra) are available in the req.query dictionary.

Python
# Example URL: /search?q=xyra&page=1
@app.get("/search")
def search(req: Request, res: Response):
    query = req.query.get("q")
    page = req.query.get("page", default="1") # Use a default value
    res.json({"searching_for": query, "page_number": page})

Supported HTTP Methods

Xyra provides decorators for all standard HTTP methods:

  • @app.get(path)
  • @app.post(path)
  • @app.put(path)
  • @app.delete(path)
  • @app.patch(path)
  • @app.options(path)
  • @app.head(path)