Extending the Admin API
Kong can be configured using a REST interface referred to as the Admin API. Plugins can extend it by adding their own endpoints to accommodate custom entities or other personalized management needs. A typical example of this is the creation, retrieval, and deletion (commonly referred to as “CRUD operations”) of API keys.
The Admin API is a application, and Kong’s level of abstraction makes it easy for you to add endpoints.
Add endpoints to the Admin API
Kong will detect and load your endpoints if they are defined in a module named:
Where:
- should be a string representing a route like
/users
(See Lapis routes & URL Patterns) for details. Notice that the path can contain interpolation parameters, like/users/:users/new
. - The
methods
sub-table contains functions, indexed by a string.- The
before
key is optional and can hold a function. If present, the function will be executed on every request that hitspath
, before any other function is invoked. - One or more functions can be indexed with HTTP method names, like
GET
orPUT
. These functions will be executed when the appropriate HTTP method andpath
is matched. If abefore
function is present on thepath
, it will be executed first. Keep in mind that functions can usekong.response.exit
to finish early, effectively cancelling the “regular” http method function. - The
on_error
key is optional and can hold a function. If present, the function will be executed when the code from other functions (either from abefore
or a “http method”) throws an error. If not present, then Kong will use a default error handler to return the errors.
- The
For example:
This code will create two Admin API endpoints in /consumers/:consumers/key-auth
, to obtain (GET
) and create (POST
) credentials associated to a given consumer. On this example the functions are provided by the kong.api.endpoints
library.
If endpoints
-provided are functions not enough, a regular Lua function can be used instead. From there you can use:
- Several functions provided by the
endpoints
module. - The
self
parameter, which is the . - And of course you can
require
any Lua modules if needed. Make sure they are compatible with OpenResty if you choose this route.
On the previous example, the path gets three functions:
- The
before
function is a custom Lua function which uses severalendpoints
-provided utilities (endpoints.handle_error
) as well as PDK functions (kong.response.exit
). It also populatesself.consumer
for the subsequent functions to use. - The
GET
function is built entirely usingendpoints
. This is possible because thebefore
has “prepared” things in advance, likeself.consumer
. - The
PUT
function populatesself.args.post.consumer
before calling theendpoints
-provided function.
Previous Caching Custom Entities