No, Lua? Python helps you quickly get started with Apache APIs IX plug-in development


As everyone familiar with Apache APIs IX knows, we have supported Java and go runner in the community before. TodayApache APISIX Python RunnerAlso here, the small partners in the community have a new choice when developing Apache APIs IX plug-ins.

As an interpretive high-level programming language, python has simple syntax, easy to use, good code readability, and good performance in cross platform, portability and development efficiency. At the same time, as a high-level programming language, it has a high degree of encapsulation abstraction and shields many underlying details (such as GC) Let’s focus more on the development of application logic in the development process.

At the same time, as a 30-year-old development language, its ecology and various modules have been very perfect. Most of our development and application scenarios can find very mature modules or solutions from the community.

Other advantages of Python will not be repeated one by one. Of course, its disadvantages are also obvious: as an explanatory language, python still has a large performance gap compared with compiled languages such as C + + and go.

Understanding: project architecture

The Apache APIs IX Python runner project can be understood as a bridge between Apache APIs IX and pythonPython RunnerPython can be directly applied to the plug-in development of Apache APIs IX. the most important thing is to let more Python developers interested in Apache APIs IX and API gateway learn more about and use Apache APIs IX through this project. The following is the architecture diagram of Apache APIs IX multilingual support.

No, Lua? Python helps you quickly get started with Apache APIs IX plug-in development

In the figure above, the workflow of Apache apifix is on the left and on the rightPlugin RunnerIt is the plug-in runner of each language, which is introduced in this paperapisix-python-plugin-runnerIt supports Python languagePlugin Runner

Configure one in Apache apifixPlugin RunnerApache APIs IX starts a child process to runPlugin Runner, the subprocess belongs to the same user as the Apache APIs IX process. When we restart or reload Apache APIs IX,Plugin RunnerWill also be restarted.

If you have configured for a given routeext-plugin-*Plug in. When the request hits the route, Apache APIs IX will be triggered to passUnix SockettowardsPlugin RunnerlaunchRPCCall. The call is divided into two phases:

  • Ext plugin pre req: executingApache APISIXBefore the built-in plug-in (Lua language plug-in)
  • Ext plugin post req: executingApache APISIXAfter the built-in plug-in (Lua language plug-in)

You can select and configure according to your needsPlugin RunnerTiming of implementation.Plugin RunnerCan handleRPCCall, create a simulated request inside it, then run the plug-in written in multiple languages, and return the results to Apache APIs IX.

The execution order of multilingual plug-ins isext-plugin-*As defined in the plug-in configuration item, like other plug-ins, they can be enabled and redefined at run time.

Installing: deploying tests

Basic operating environment: Apache apifix 2.7, python 3.6+

For the installation and deployment of Apache APIs IX, please refer to the official Apache APIs IX document: how to build Apache APIs IX(…)Deploy.

1. Download and install Python runner

$ git clone
$ cd apisix-python-plugin-runner
$ make install

2. Configure Python runner

  • Development mode configuration
  1. Run Python runner
$ cd /path/to/apisix-python-plugin-runner
$ APISIX_LISTEN_ADDRESS=unix:/tmp/runner.sock python3 apisix/ start
  1. Modify Apache apifix configuration file
$ vim /path/to/apisix/conf/config.yaml
    - name: "admin"
      key: edd1c9f034335f136f87ad84b625c8f1
      role: admin
  path_for_test: /tmp/runner.sock
  • Production mode configuration
  1. Modify Apache apifix configuration file
$ vim /path/to/apisix/conf/config.yaml
    - name: "admin"
      key: edd1c9f034335f136f87ad84b625c8f1
      role: admin
  cmd: [ "python3", "/path/to/apisix-python-plugin-runner/apisix/", "start" ]
  1. Python runner configuration (optional)

If necessaryLog LevelorUnix Domain SocketEnvironment variable adjustment can be modifiedRunnerConfiguration file for

$ vim /path/to/apisix-python-plugin-runner/apisix/config.yaml
  file: $env.APISIX_LISTEN_ADDRESS # Environment variable or absolute path

  level: debug # error warn info debug

3. Start Python runner

$ cd /path/to/apisix
# Start or Restart
$ ./bin/apisix [ start | restart ]

Just start or restart Apache apifix. At this time, Apache apifix andPython RunnerConfiguration is complete and started.

4. Test Python runner

  1. Configure Apache APIs IX routing and plug-in information
#   Use the default demo plug-in for testing
$ curl -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  "uri": "/get",
  "plugins": {
    "ext-plugin-pre-req": {
      "conf": [
        { "name": "stop", "value":"{\"body\":\"hello\"}"}
  "upstream": {
        "type": "roundrobin",
        "nodes": {
            "": 1
  • plugins.ext-plugin-pre-req.confbyRunnerPlug in configuration,confMultiple plug-ins can be set for array format at the same time.
  • In the plug-in configuration objectnameIs the plug-in name, which must be consistent with the plug-in code file and object name.
  • In the plug-in configuration objectvalueFor plug-in configuration, you canJSONcharacter string.

2. Access verification

$ curl -i
HTTP/1.1 200 OK
Date: Fri, 13 Aug 2021 13:39:18 GMT
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
accept: */*
user-agent: curl/7.64.1
X-Resp-A6-Runner: Python
Server: APISIX/2.7

Hello, Python Runner of APISIX

Practice: plug in development

1. Plug in directory


In this directory.pyThe file will be loaded automatically.

2. Plug in Example


3. Plug in format

from apisix.runner.plugin.base import Base
from apisix.runner.http.request import Request
from apisix.runner.http.response import Response

class Stop(Base):
    def __init__(self):
        Example of `stop` type plugin, features:
            This type of plugin can customize response `body`, `header`, `http_code`
            This type of plugin will interrupt the request
        super(Stop, self).__init__(self.__class__.__name__)

    def filter(self, request: Request, response: Response):
        The plugin executes the main function
        :param request:
            request parameters and information
        :param response:
            response parameters and information
        #   In the plug-in, you can  ` self.config`   Get the configuration information. If the plug-in is configured as JSON, it will be automatically converted to dictionary structure
        # print(self.config)

        #   Set response header information
        headers = request.headers
        headers["X-Resp-A6-Runner"] = "Python"
        response.headers = headers

        #   Set response body information
        response.body = "Hello, Python Runner of APISIX"

        #   Set response status code
        response.status_code = 201

        #   By calling  ` self.stop()`   Interrupt the request process and immediately respond to the request to the client
        #   If the call is not displayed  ` self.stop()`   or   Display call  ` Self. Rewrite() ` continue the request
        #   Default to  ` self.rewrite()`

4. Plug in specifications and precautions

  • The implementation plug-in object must inheritBaseclass
  • The plug-in must implementfilterfunction
  • filterFunction arguments can only containRequestandResponseClass object as parameter
  • RequestObject parameters can get request information
  • ResponseObject parameters can set response information
  • self.configYou can get plug-in configuration information
  • filterCall in functionself.stop()Will immediately interrupt the request and respond to the data.
  • filterCall in functionself.rewrite()The request will continue when.

Contribution: participation in the project

At present, the runner of Apache apisix languages is still in the early development stage, and we will gradually improve its functions. A successful open source project is inseparable from your participation and contribution. You are welcome to participateApache APISIX RunnerLet’s build a bridge between Apache apisid and various languages. Refer to the following for specific items:

Recommended reading

Author introduction

Shuai Jinchao, Apache apisik PMC

About Apache APIs IX

Apache apisix is a dynamic, real-time, high-performance open source API gateway, which provides rich traffic management functions such as load balancing, dynamic upstream, gray publishing, service fusing, identity authentication, observability and so on. Apache APIs IX can help enterprises process API and micro service traffic quickly and safely, including gateway, kubernetes ingress and service grid.

Hundreds of enterprises around the world have used Apache apisix to handle key business traffic, including finance, Internet, manufacturing, retail, operators, etc., such as NASA, European Union digital factory, China aerospace, China Mobile, Tencent, Huawei, microblog, Netease, shell search, 360, Taikang, Naixue’s tea, etc.

More than 200 contributors have jointly created Apache APIs IX, the world’s most active open source gateway project. Smart developers! Join this active and diverse community and bring more beautiful things to the world!