kong.tools.responses

Kong helper methods to send HTTP responses to clients.

Can be used in the proxy (core/resolver), plugins or Admin API. Most used HTTP status codes and responses are implemented as helper methods.

local responses = require "kong.tools.responses"

-- In an Admin API endpoint handler, or in one of the plugins' phases.
-- the return keyword is optional since the execution will be stopped
-- anyways. It simply improves code readability.
return responses.send_HTTP_OK()

-- Or:
return responses.send_HTTP_NOT_FOUND("No entity for given id")

-- Raw send() helper:
return responses.send(418, "This is a teapot")

Functions

send (status_code, body, raw, headers) Send a response with any status code or body, Not all status codes are available as sugar methods, this function can be used to send any response.

Tables

status_codes Define the most common HTTP status codes for sugar methods.

Functions


send

Send a response with any status code or body, Not all status codes are available as sugar methods, this function can be used to send any response. If the status_code parameter is in the 5xx range, it is expectde that the content parameter be the error encountered. It will be logged and the response body will be empty. The user will just receive a 500 status code. Will call ngx.say and ngx.exit, terminating the current context.
Parameters:
  • status_code number HTTP status code to send
  • body A string or table which will be the body of the sent response. If table, the response will be encoded as a JSON object. If string, the response will be a JSON object and the string will be contained in the message property. Except if the raw parameter is set to true.
  • raw boolean If true, send the body as it is.
  • headers table Response headers to send.
Returns:
  • ngx.exit (Exit current context)
See also:

Tables


status_codes

Define the most common HTTP status codes for sugar methods. Each of those status will generate a helper method (sugar) attached to this exported module prefixed with send_. Final signature of those methods will be send_<status_code_key>(message, raw, headers). See send for more details on those parameters.
Fields:
  • HTTP_OK 200 OK
  • HTTP_CREATED 201 Created
  • HTTP_NO_CONTENT 204 No Content
  • HTTP_BAD_REQUEST 400 Bad Request
  • HTTP_UNAUTHORIZED 401 Unauthorized
  • HTTP_FORBIDDEN 403 Forbidden
  • HTTP_NOT_FOUND 404 Not Found
  • HTTP_METHOD_NOT_ALLOWED 405 Method Not Allowed
  • HTTP_CONFLICT 409 Conflict
  • HTTP_UNSUPPORTED_MEDIA_TYPE 415 Unsupported Media Type
  • HTTP_INTERNAL_SERVER_ERROR Internal Server Error
Usage:
  • return responses.send_HTTP_OK()
  • return responses.HTTP_CREATED("Entity created")
  • return responses.HTTP_INTERNAL_SERVER_ERROR()

Keep up with the latest features