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.
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
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.
Method
Description
context
HTTP Server context. Allows access to the raw Request and Response objects
method
HTTP Request Method
header
Gets all HTTP Headers
json
Gets request body as string
cookies
Gets request cookies
content_type(type : String)
Sets the content type of the response
header(key : String, value : String)
Sets response header
redirect(to location : String, status : Int32 = 301)
Redirect requests to a new resource
cookie(cookie : HTTP::Cookie)
Sets response cookie
status(status : Int32)
Sets response status
error(message : String, status : Int32 = 400, errors = [] of String)
Renders a response error
The call method
Every endpoint must define a call method that returns a Response object.
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.
class UserEndpoint
include Endpoint(UserRequest, UserResponse)
def call : UserResponse
user_request.name
end
end
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
For flexibility Azu allows you to define routes outside of Endpoints.
Route Helpers
Last updated
Was this helpful?