Request and Response

In Xyra, each route handler receives Request and Response objects, giving you full control over incoming data and outgoing responses.

The Request Object

The Request object provides a convenient API for accessing information about the incoming HTTP request.

Request Properties

  • req.params: A dictionary of route parameters (e.g., from /users/{id}).
  • req.query: A dictionary of URL query parameters (e.g., from /search?q=...).
  • req.headers: A dictionary of request headers.
  • req.method: The HTTP method of the request (e.g., 'GET', 'POST').
  • req.url: The full URL of the request.

Reading the Request Body

For methods like POST or PUT, you can asynchronously read the request body.

Python
@app.post("/users")
async def create_user(req: Request, res: Response):
    # Asynchronously reads the request body as JSON
    user_data = await req.json() 
    
    # You can also read form data
    # form_data = await req.form()

    res.status(201).json({"received": user_data})

The Response Object

The Response object provides methods for sending a response back to the client.

Sending Responses

Xyra offers several intuitive methods for sending different types of content.

  • res.text(content): Sends a plain text response.
  • res.json(data): Sends a JSON response with the correct `Content-Type` header.
  • res.html(content): Sends an HTML response.
  • res.render(template_name, **context): Renders an HTML template (see Templating page).
Python
@app.get("/api/health")
def health_check(req: Request, res: Response):
    res.json({"status": "ok"})

Setting Status and Headers

You can chain methods to fluently set the HTTP status code and response headers.

Python
@app.post("/create-item")
def create_item(req: Request, res: Response):
    # Method chaining for a clean API
    res.status(201).header("X-Custom-Header", "MyValue").json({"message": "Created"})

Redirects

To redirect the client to a different URL, use the redirect() method.

Python
@app.get("/old-page")
def old_page(req: Request, res: Response):
    # This will send a 302 Found status code by default
    res.redirect("/new-page")