Custom Plugin Development in APISIX
Introduction
APISIX's plugin architecture allows you to extend its functionality to meet your specific needs. This guide will walk you through the process of creating custom plugins using Lua, from basic concepts to advanced implementations.
Prerequisites
- APISIX installed and configured
- Basic knowledge of Lua programming
- Understanding of HTTP concepts
- Familiarity with APISIX architecture
1. Plugin Structure
A basic APISIX plugin consists of these components:
local plugin_name = {
version = 0.1,
priority = 2000,
name = "my-plugin",
schema = {
type = "object",
properties = {
key = {type = "string"}
}
}
}
function plugin_name.check_schema(conf)
return core.schema.check(plugin_name.schema, conf)
end
function plugin_name.access(conf, ctx)
-- Plugin logic here
end
return plugin_name
2. Plugin Lifecycle
APISIX plugins can hook into different phases of the request lifecycle:
rewrite
: URL rewriting phaseaccess
: Request processing phaseheader_filter
: Response header modificationbody_filter
: Response body modificationlog
: Logging phase
3. Example Custom Plugin
Here's a simple request transformer plugin:
local core = require "apisix.core"
local plugin_name = {
version = 0.1,
priority = 2000,
name = "request-transformer",
schema = {
type = "object",
properties = {
add_headers = {
type = "object",
patternProperties = {
["^.*$"] = { type = "string" }
}
}
}
}
}
function plugin_name.access(conf, ctx)
for header_name, header_value in pairs(conf.add_headers) do
core.request.set_header(ctx, header_name, header_value)
end
end
return plugin_name
4. Testing Plugins
Create test cases for your plugin:
-- In t/plugin/test-my-plugin.t
use t::APISIX 'no_plan';
repeat_each(1);
no_long_string();
no_shuffle();
add_block_preprocessor(sub {
my ($block) = @_;
});
run_tests();
__DATA__
=== TEST 1: sanity check
--- config
location /t {
content_by_lua_block {
local plugin = require("apisix.plugins.my-plugin")
local ok, err = plugin.check_schema({key = "value"})
ngx.say(ok and "ok" or err)
}
}
--- response_body
ok
5. Best Practices
- Follow APISIX coding standards
- Implement proper error handling
- Write comprehensive tests
- Document your plugin thoroughly
- Consider performance implications
Conclusion
Custom plugins allow you to extend APISIX's functionality to meet your specific requirements. By following this guide and best practices, you can create reliable and efficient plugins for your API gateway.
View APISIX Documentation on GitHub