Endpoints

Endpoints is a simple module that defines the resource, and allows you to access the Request object and build the Response.

Endpoints is a simple module that defines the resource, and allows you to access the Request object and build the Response.

The endpoint is the final stage of the request process Each endpoint is the location from which APIs can access the resources of your application to carry out their function.

Endpoints as Contracts

To ensure correctness Endpoints are designed with the Request and Response pattern in mind you can think of it as input and output to a function, where the request is the input and the response is the output.

 include Endpoint(UserRequest, UserResponse)

Request and Response objects are type-safe objects that can be designed by contract.

/my_app/endpoints/user_endpoint.cr
module MyApp
  struct UserRequest
    include Request
  end
  
  class UserEndpoint
    include Endpoint(UserRequest, UserResponse)
    
    get "/users"
  end
end

Creating Endpoints

An Endpoint requires at a minimum a Request and Response Object

/my_app/endpoints/user_endpoint.cr
class UserEndpoint
    include Endpoint(UserRequest, UserResponse)
    
    def call : UserResponse
        # .. your code here ..
    end
end

Basic Methods

The endpoint gives you access to a wide rage of functions to allow you inspect the request and modify the response.

The call method

Every endpoint must define a call method that returns a Response object.

/my_app/endpoints/user_endpoint.cr
def call : UserResponse
# .. your code here ..
end

Request Object

A request object encapsulates the structure of the incoming HTTP request as needed per your application, allowing you to inspect, validate and ensuring correctness. Read more about Requests

struct UserRequest
  include Request
  
  getter name : String
  
  validate name, message: "Param name must be present.", presence: true
end

The endpoint will contain a user_request method that returns an instance of the UserRequest object.

/my_app/endpoints/user_endpoint.cr
class UserEndpoint
  include Endpoint(UserRequest, UserResponse)

  def call : UserResponse
    user_request.name
  end
end

Read more about Requests

Inline Routing

The most basic Azu routes accept a URI and a HTTP::Handler.

Routes can be defined withing Endpoints. Having routes defined close to the class that uses it allows for code cohesiveness and readability

module MyApp
  class UserEndpoint
    include Endpoint(UserRequest, UserResponse)
    
    get "/users"
  end
end

All HTTP verbs are available as macro methods within Endpoints.

For flexibility Azu allows you to define routes outside of Endpoints.

Route Helpers

Last updated