Params

Access request parameters from the request body, query string, path

Params, short for parameters, allow you to access data sent by the client with the request. Requests can have parameters in different places, intuitively the params can be accessed by the attribute context location:

Params can come from:

  • Request path (eg. /books/:id)

  • Query string (eg. /books?title=Hanami)

  • Request body (eg. a POST request to /books)

Other than Path and Query parameters, all other parameters are parsed depending on the "Content-Type" header

Access to Parameters

Params provide hash-like access to the request attributes. Since attributes can be expected in different contexts of the request such as path, body, and query, the lookup happens in the following order of precedence.

  1. Form

  2. Path

  3. Query

To access the value of a param, we can use the subscriber operator #[].

Given an Endpoint with a path of "/users/:id"

module MyApp
  struct UserRequest
    include Request
  end
  
  class UserEndpoint
    include Endpoint(UserRequest, UserResponse)
    
    get "/users/:id"
    
    def call : UserResponse
      id = params["id"]
    end
  end
end

If we visit /users/john, we should see path string:john.

JSON Parameters

If you're writing a web service application, you might find yourself more comfortable accepting parameters in JSON format. If the "Content-Type" header of your request is set to "application/json", will automatically be loaded into the params.json object.

So for example, if you are sending this JSON content:

{ "company": { "name": "acme", "address": "123 Carrot Street" } }

The params object will contain a string with the content of the JSON.

Note: Azu does not convert the params.json string into a JSON ANY object, and instead the developer can decide how to best parse.

Last updated