Api Integration With Apache Apisix

Gopal GautamGopal Gautam
6 min read

What is an Apache APISIX?

Apache APISIX is a dynamic, high-performance API gateway that is part of the Apache Software Foundation. It is designed to handle API traffic for web, mobile, and IoT applications. APISIX provides advanced features such as dynamic routing, traffic control, load balancing, rate limiting, authentication, and monitoring. It is built to be extensible and customizable, allowing developers to easily add new functionality and integrate with existing systems. APISIX is used to manage and secure APIs, optimize performance, and ensure high availability for API-based applications.

Why We Use Apache APISIX?

Integrating with Apache APISIX for API management offers several benefits, such as:

  1. Traffic Management: APISIX provides features like load balancing, rate limiting, and traffic control, which help manage and optimize API traffic.

  2. Security: APISIX offers security features like JWT authentication, rate limiting, and IP whitelisting, which help secure your APIs from unauthorized access and attacks.

  3. Monitoring and Analytics: APISIX provides monitoring and analytics tools that help you track API usage, performance, and errors, enabling you to make data-driven decisions to improve your APIs.

  4. Scalability: APISIX is designed for high performance and scalability, making it suitable for handling large volumes of API traffic.

If you choose not to integrate with Apache APISIX, you may face the following drawbacks:

  1. Limited Traffic Control: Without APISIX, you'll have limited control over API traffic, which can lead to issues like traffic spikes and poor performance.

  2. Security Risks: Without the security features of APISIX, your APIs may be more vulnerable to unauthorized access and attacks.

  3. Lack of Monitoring and Analytics: Without APISIX, you won't have access to monitoring and analytics tools, making it difficult to track API usage, performance, and errors.

  4. Scalability Challenges: Without APISIX, scaling your API to handle large volumes of traffic may be more challenging and less efficient.

Overall, integrating with Apache APISIX can help you improve the performance, security, and scalability of your APIs, while choosing not to integrate may result in limited traffic control, security risks, and scalability challenges.

Installation:

To install Apache APISIX, you can follow these steps:

  1. Prepare Configuration Files:

    • Ensure you have the necessary configuration files in place. For example, in the ./apisix_conf directory, you should have a config.yaml file
apisix:
  node_listen: 9080              # APISIX listening port
  enable_ipv6: false

  enable_control: true
  control:
    ip: "0.0.0.0"
    port: 9095

deployment:
  admin:
    allow_admin:               # http://nginx.org/en/docs/http/ngx_http_access_module.html#allow
      - 0.0.0.0/0              # We need to restrict ip access rules for security. 0.0.0.0/0 is for test.

    admin_key:
      - name: "admin"
        key: 7457a0ca-912f-4210-7bdb-13e845ea1c3d
        role: admin                 # admin: manage all configuration data

      - name: "viewer"
        key: 4054f7cf07e344346cd3f287985e76a2
        role: viewer

  etcd:
    host:                           # it's possible to define multiple etcd hosts addresses of the same etcd cluster.
      - "http://etcd:2379"          # multiple etcd address
    prefix: "/apisix"               # apisix configurations prefix
    timeout: 30                     # 30 seconds

plugin_attr:
  prometheus:
    export_addr:
      ip: "0.0.0.0"
      port: 9091

in the ./dashboard_conf directory, you should have a conf.yaml file.

conf:
  listen:
    host: 0.0.0.0     # `manager api` listening ip or host name
    port: 9000          # `manager api` listening port
  allow_list:           # If we don't set any IP list, then any IP access is allowed by default.
    - 0.0.0.0/0
  etcd:
    endpoints:          # supports defining multiple etcd host addresses for an etcd cluster
      - "http://etcd:2379"
                          # yamllint disable rule:comments-indentation
                          # etcd basic auth info
    # username: "root"    # ignore etcd username if not enable etcd auth
    # password: "123456"  # ignore etcd password if not enable etcd auth
    mtls:
      key_file: ""          # Path of your self-signed client side key
      cert_file: ""         # Path of your self-signed client side cert
      ca_file: ""           # Path of your self-signed ca cert, the CA is used to sign callers' certificates
    # prefix: /apisix     # apisix config's prefix in etcd, /apisix by default
  log:
    error_log:
      level: warn       # supports levels, lower to higher: debug, info, warn, error, panic, fatal
      file_path:
        logs/error.log  # supports relative path, absolute path, standard output
                        # such as: logs/error.log, /tmp/logs/error.log, /dev/stdout, /dev/stderr
    access_log:
      file_path:
        logs/access.log  # supports relative path, absolute path, standard output
                         # such as: logs/access.log, /tmp/logs/access.log, /dev/stdout, /dev/stderr
                         # log example: 2020-12-09T16:38:09.039+0800    INFO    filter/logging.go:46    /apisix/admin/routes/r1    {"status": 401, "host": "127.0.0.1:9000", "query": "asdfsafd=adf&a=a", "requestId": "3d50ecb8-758c-46d1-af5b-cd9d1c820156", "latency": 0, "remoteIP": "127.0.0.1", "method": "PUT", "errs": []}
  security:
      # access_control_allow_origin: "http://httpbin.org"
      # access_control_allow_credentials: true          # support using custom cors configration
      # access_control_allow_headers: "Authorization"
      # access_control-allow_methods: "*"
      # x_frame_options: "deny"
      content_security_policy: "default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; frame-src *"  # You can set frame-src to provide content for your grafana panel.

authentication:
  secret:
    secret              # secret for jwt token generation.
                        # NOTE: Highly recommended to modify this value to protect `manager api`.
                        # if it's default value, when `manager api` start, it will generate a random string to replace it.
  expire_time: 3600     # jwt token expire time, in second
  users:                # yamllint enable rule:comments-indentation
    - username: admin   # username and password for login `manager api`
      password: admin
    - username: user
      password: user

plugins:                          # plugin list (sorted in alphabetical order)
  - api-breaker
  - authz-keycloak
  - basic-auth
  - batch-requests
  - consumer-restriction
  - cors
  # - dubbo-proxy
  - echo
  # - error-log-logger
  # - example-plugin
  - fault-injection
  - grpc-transcode
  - hmac-auth
  - http-logger
  - ip-restriction
  - jwt-auth
  - kafka-logger
  - key-auth
  - limit-conn
  - limit-count
  - limit-req
  # - log-rotate
  # - node-status
  - openid-connect
  - prometheus
  - proxy-cache
  - proxy-mirror
  - proxy-rewrite
  - redirect
  - referer-restriction
  - request-id
  - request-validation
  - response-rewrite
  - serverless-post-function
  - serverless-pre-function
  # - skywalking
  - sls-logger
  - syslog
  - tcp-logger
  - udp-logger
  - uri-blocker
  - wolf-rbac
  - zipkin
  - server-info
  - traffic-split

Create a Docker Compose File:

Open the docker-compose.yml file using a text editor.

version: "3"

services:
  apisix-dashboard:
    image: apache/apisix-dashboard:3.0.0-alpine
    restart: always
    volumes:
    - ./dashboard_conf/conf.yaml:/usr/local/apisix-dashboard/conf/conf.yaml
    ports:
    - "9000:9000"
    networks:
      apisix:

  apisix:
    image: apache/apisix:${APISIX_IMAGE_TAG:-3.1.0-debian}
    restart: always
    volumes:
      - ./apisix_conf/config.yaml:/usr/local/apisix/conf/config.yaml:ro
    depends_on:
      - etcd
    ##network_mode: host
    ports:
      - "9180:9180/tcp"
      - "9080:9080/tcp"
      - "9091:9091/tcp"
      - "9443:9443/tcp"
      - "9095:9092/tcp"
    networks:
      apisix:

  etcd:
    image: bitnami/etcd:3.4.15
    restart: always
    volumes:
      - etcd_data:/bitnami/etcd
    environment:
      ETCD_ENABLE_V2: "true"
      ALLOW_NONE_AUTHENTICATION: "yes"
      ETCD_ADVERTISE_CLIENT_URLS: "http://etcd:2379"
      ETCD_LISTEN_CLIENT_URLS: "http://0.0.0.0:2379"
    ports:
      - "2379:2379/tcp"
    networks:
      apisix:

networks:
  apisix:
    driver: bridge

volumes:
  etcd_data:
    driver: local

Start Apache APISIX:

Run the following command to start Apache APISIX and its dashboard:

docker-compose up -d

This command will start Apache APISIX and its dashboard in detached mode, meaning they will run in the background.

Access the Dashboard:

Once Apache APISIX and its dashboard are running, you can access the dashboard by navigating to http://ip:9000 in your web browser.

username: admin password: admin

Example:

To set up and run the Flask application (hellodjango.py), follow these steps:

  1. Install Flask:

    • If Flask is not already installed, install it using pip:

        pip install Flask
      
  2. Create the Flask Application File:

    • Create a file named hellodjango.py and add the following code to it:

        from flask import Flask
      
        app = Flask(__name__)
      
        @app.route("/django")
        def hello_world():
            return "<p>Hello, django!</p>"
      
        if __name__ == "__main__":
            app.run(host='0.0.0.0', port=2020)
      
  3. Run the Flask Application:

    • Run the Flask application using the following command:

        python hellodjango.py
      
    • This command will start the Flask development server, and your application will be accessible at http://ip:2020/django.

  4. Testing the Flask Application:

    • Open a web browser or use a tool like curl to send a GET request to http://localhost:2020/django. You should see the "Hello, django!" message displayed in your browser or terminal.

To set up your Flask application (hellodjango.py) with Apache APISIX, follow these steps:

  1. Create Upstream in Apache APISIX:

    • Use the following curl command to create an upstream named 1 pointing to IP:2020:
    curl "http://IP:9180/apisix/admin/upstreams/1" -H "X-API-KEY: <Put-API-KEY>" -X PUT -d '
           {
             "type": "roundrobin",
             "scheme": "http",
             "nodes": {
               "IP:2020": 1
             }
        }'
  1. Create Route in Apache APISIX:

    • Use the following curl command to create a route that forwards requests with the host and the URI /django to the upstream with ID 1:
    curl "http://IP:9180/apisix/admin/routes/1" -H "X-API-KEY: <Put-API-KEY>" -X PUT -d '
    {
      "methods": ["GET"],
      "host": "IP",
      "uri": "/django",
      "upstream_id": "1"
    }'
  1. Test the Setup:

    • open your browser type http://IP:9080/django.
0
Subscribe to my newsletter

Read articles from Gopal Gautam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gopal Gautam
Gopal Gautam

Hii I am a backend/DevOps engineer.I have a experience with development and automation.I mostly work with Python, django, Cloud based technologies.