Return Different Formats

This guide shows you how to return JSON, HTML, text, and other response formats.

JSON Response

Return JSON data:

struct JsonEndpoint
  include Azu::Endpoint(EmptyRequest, Azu::Response::Json)

  get "/api/data"

  def call
    json({
      message: "Hello",
      timestamp: Time.utc.to_rfc3339
    })
  end
end

Custom JSON Response

struct UserResponse
  include Azu::Response

  def initialize(@user : User)
  end

  def render
    {
      id: @user.id,
      name: @user.name,
      email: @user.email
    }.to_json
  end
end

Text Response

Return plain text:

HTML Response

Return HTML content:

Using Templates

Empty Response

Return no content (204):

Content Negotiation

Return different formats based on Accept header:

Setting Headers

Add custom response headers:

Redirect Response

Redirect to another URL:

File Download

Return a file for download:

See Also

Last updated

Was this helpful?