Create an Endpoint

This guide shows you how to create type-safe HTTP endpoints in Azu.

Basic Endpoint

Create an endpoint by including Azu::Endpoint with request and response types:

struct HelloEndpoint
  include Azu::Endpoint(EmptyRequest, Azu::Response::Text)

  get "/"

  def call
    text "Hello, World!"
  end
end

Endpoint with JSON Response

struct UserEndpoint
  include Azu::Endpoint(EmptyRequest, UserResponse)

  get "/users/:id"

  def call : UserResponse
    user_id = params["id"].to_i64
    user = User.find(user_id)

    if user
      UserResponse.new(user)
    else
      raise Azu::Response::NotFound.new("/users/#{user_id}")
    end
  end
end

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

HTTP Method Macros

Use macros to declare the HTTP method:

Accessing Request Data

Route Parameters

Query Parameters

Request Headers

Setting Response Status

Registering Endpoints

Add endpoints to your application:

See Also

Last updated

Was this helpful?