# Public API

`public-api` 插件用于暴露内部 API 端点，使其可公开访问。该插件的主要用途之一是暴露由其他插件创建的内部端点。

## 示例[​](#示例 "示例的直接链接")

以下示例展示了如何在不同场景下配置 `public-api`。

### 在自定义端点暴露 Prometheus 指标[​](#在自定义端点暴露-prometheus-指标 "在自定义端点暴露 Prometheus 指标的直接链接")

以下示例演示了如何禁用默认在 `9091` 端口暴露端点的 Prometheus 导出服务器，并在 APISIX 用于监听其他客户端请求的 `9080` 端口上，通过新的公共 API 端点暴露 APISIX Prometheus 指标。

你还需要配置路由，使得内部端点 `/apisix/prometheus/metrics` 通过自定义端点暴露。

警告

如果收集的指标数量较大，该插件可能会占用大量 CPU 资源进行指标计算，并对常规请求的处理产生负面影响。

为解决此问题，APISIX 使用 [特权进程](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/process.md#enable_privileged_agent) 并将指标计算卸载到单独的进程。如果你使用配置文件中 `plugin_attr.prometheus.export_addr` 下配置的指标端点，此优化将自动应用。如果通过 `public-api` 插件暴露指标端点，则无法享受此优化。

要通过 `public-api` 暴露指标，请先禁用默认的 Prometheus 导出服务器：

* Host or Docker
* Kubernetes (Helm)

在网关配置文件中新增或更新以下配置：

config.yaml

```
plugin_attr:

  prometheus:

    enable_export_server: false
```

重新加载网关以使更改生效。

对于 Helm 部署，请更新用于渲染 `plugin_attr.prometheus` 的 Chart values，并保留 values 文件中的其他配置。

对于 APISIX Helm Chart，设置以下 values：

values.yaml

```
apisix:

  pluginAttrs:

    prometheus:

      enable_export_server: false
```

对于 API7 网关 Helm Chart，设置以下 values：

values.yaml

```
pluginAttrs:

  prometheus:

    enable_export_server: false
```

然后使用当前网关 release 对应的 Chart 应用 values 文件：

```
helm upgrade <release-name> <chart-name> -n <namespace> -f values.yaml
```

接下来，创建一个使用 `public-api` 插件的路由，为 APISIX 指标暴露一个公共 API 端点：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "prometheus-metrics",

    "uri": "/prometheus_metrics",

    "plugins": {

      "public-api": {

        "uri": "/apisix/prometheus/metrics"

      }

    }

  }'
```

adc.yaml

```
services:

  - name: public-api-metrics-service

    routes:

      - name: prometheus-metrics

        uris:

          - /prometheus_metrics

        plugins:

          public-api:

            uri: /apisix/prometheus/metrics

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=public-api-metrics
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=public-api-metrics
```

* Gateway API
* APISIX CRD

public-api-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  name: httpbin-external-domain

  namespace: aic

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      protocol: TCP

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: prometheus-metrics

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /prometheus_metrics

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: public-api-metrics-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: public-api-metrics-plugin-config

spec:

  plugins:

    - name: public-api

      config:

        uri: /apisix/prometheus/metrics
```

public-api-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: prometheus-metrics

spec:

  ingressClassName: apisix

  http:

    - name: prometheus-metrics

      match:

        paths:

          - /prometheus_metrics

      plugins:

        - name: public-api

          enable: true

          config:

            uri: /apisix/prometheus/metrics
```

应用配置：

```
kubectl apply -f public-api-ic.yaml
```

❶ 将路由 `uri` 设置为自定义端点路径。

❷ 将插件 `uri` 设置为要暴露的内部端点。

ADC 和 Gateway API 标签页包含常规后端。当插件自行处理请求时，不会联系该后端。请验证下方的插件特定结果；仅收到后端响应并不能证明插件已运行。

向自定义指标端点发送请求：

```
curl "http://127.0.0.1:9080/prometheus_metrics"
```

你应该看到类似如下的输出：

```
# HELP apisix_http_requests_total The total number of client requests since APISIX started

# TYPE apisix_http_requests_total gauge

apisix_http_requests_total 1

# HELP apisix_nginx_http_current_connections Number of HTTP connections

# TYPE apisix_nginx_http_current_connections gauge

apisix_nginx_http_current_connections{state="accepted"} 1

apisix_nginx_http_current_connections{state="active"} 1

apisix_nginx_http_current_connections{state="handled"} 1

apisix_nginx_http_current_connections{state="reading"} 0

apisix_nginx_http_current_connections{state="waiting"} 0

apisix_nginx_http_current_connections{state="writing"} 1

...
```

### 暴露批量请求端点[​](#暴露批量请求端点 "暴露批量请求端点的直接链接")

以下示例使用 `public-api` 为 `batch-requests` 暴露端点。客户端可以通过一次 HTTP 调用向网关发送多个请求并接收合并结果。

网关必须在静态插件列表中加载 `batch-requests`。APISIX 默认不加载该插件。请保留现有插件列表，添加 `batch-requests`，然后重新加载网关，再继续后续操作。

创建一个指向 httpbin `/anything` 端点的示例路由进行验证：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "httpbin-anything",

    "uri": "/anything",

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - name: httpbin-anything

        uris:

          - /anything

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=public-api-batch-target
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=public-api-batch-target
```

* Gateway API
* APISIX CRD

public-api-httpbin-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: httpbin-anything

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

public-api-httpbin-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: httpbin-anything

spec:

  ingressClassName: apisix

  http:

    - name: httpbin-anything

      match:

        paths:

          - /anything

      upstreams:

        - name: httpbin-external-domain
```

应用配置：

```
kubectl apply -f public-api-httpbin-ic.yaml
```

创建一个使用 `public-api` 插件的路由，并将路由 `uri` 设置为要暴露的内部端点：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "batch-requests",

    "uri": "/apisix/batch-requests",

    "plugins": {

      "public-api": {}

    }

  }'
```

adc.yaml

```
services:

  - name: public-api-batch-service

    routes:

      - name: batch-requests

        uris:

          - /apisix/batch-requests

        plugins:

          public-api: {}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=public-api-batch
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=public-api-batch
```

* Gateway API
* APISIX CRD

public-api-batch-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  name: httpbin-external-domain

  namespace: aic

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      protocol: TCP

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: public-api-batch-plugin-config

spec:

  plugins:

    - name: public-api

      config: {}

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: batch-requests

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /apisix/batch-requests

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: public-api-batch-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

public-api-batch-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: batch-requests

spec:

  ingressClassName: apisix

  http:

    - name: batch-requests

      match:

        paths:

          - /apisix/batch-requests

      plugins:

        - name: public-api

          enable: true
```

应用配置：

```
kubectl apply -f public-api-batch-ic.yaml
```

向暴露的批量请求端点发送一个由 GET 和 POST 请求组成的管道请求：

```
curl "http://127.0.0.1:9080/apisix/batch-requests" -X POST -d '

{

  "pipeline": [

    {

      "method": "GET",

      "path": "/anything"

    },

    {

      "method": "POST",

      "path": "/anything",

      "body": "a post request"

    }

  ]

}'
```

你应该会收到两个请求的响应，类似如下：

```
[

  {

    "reason": "OK",

    "body": "{\n  \"args\": {}, \n  \"data\": \"\", \n  \"files\": {}, \n  \"form\": {}, \n  \"headers\": {\n    \"Accept\": \"*/*\", \n    \"Host\": \"127.0.0.1\", \n    \"User-Agent\": \"curl/8.6.0\", \n    \"X-Amzn-Trace-Id\": \"Root=1-67b6e33b-5a30174f5534287928c54ca9\", \n    \"X-Forwarded-Host\": \"127.0.0.1\"\n  }, \n  \"json\": null, \n  \"method\": \"GET\", \n  \"origin\": \"192.168.107.1, 43.252.208.84\", \n  \"url\": \"http://127.0.0.1/anything\"\n}\n",

    "headers": {

      ...

    },

    "status": 200

  },

  {

    "reason": "OK",

    "body": "{\n  \"args\": {}, \n  \"data\": \"a post request\", \n  \"files\": {}, \n  \"form\": {}, \n  \"headers\": {\n    \"Accept\": \"*/*\", \n    \"Content-Length\": \"14\", \n    \"Host\": \"127.0.0.1\", \n    \"User-Agent\": \"curl/8.6.0\", \n    \"X-Amzn-Trace-Id\": \"Root=1-67b6e33b-0eddcec07f154dac0d77876f\", \n    \"X-Forwarded-Host\": \"127.0.0.1\"\n  }, \n  \"json\": null, \n  \"method\": \"POST\", \n  \"origin\": \"192.168.107.1, 43.252.208.84\", \n  \"url\": \"http://127.0.0.1/anything\"\n}\n",

    "headers": {

      ...

    },

    "status": 200

  }

]
```

如果你想在自定义端点暴露批量请求端点，可以如下创建带有 `public-api` 插件的路由：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "batch-requests",

    "uri": "/batch-requests",

    "plugins": {

      "public-api": {

        "uri": "/apisix/batch-requests"

      }

    }

  }'
```

adc.yaml

```
services:

  - name: public-api-batch-service

    routes:

      - name: batch-requests

        uris:

          - /batch-requests

        plugins:

          public-api:

            uri: /apisix/batch-requests

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=public-api-batch
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=public-api-batch
```

* Gateway API
* APISIX CRD

public-api-batch-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  name: httpbin-external-domain

  namespace: aic

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      protocol: TCP

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: batch-requests

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /batch-requests

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: public-api-batch-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: public-api-batch-plugin-config

spec:

  plugins:

    - name: public-api

      config:

        uri: /apisix/batch-requests
```

public-api-batch-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: batch-requests

spec:

  ingressClassName: apisix

  http:

    - name: batch-requests

      match:

        paths:

          - /batch-requests

      plugins:

        - name: public-api

          enable: true

          config:

            uri: /apisix/batch-requests
```

应用配置：

```
kubectl apply -f public-api-batch-ic.yaml
```

❶ 将路由 `uri` 设置为自定义端点路径。

❷ 将插件 `uri` 设置为要暴露的内部端点。

现在批量请求端点应该暴露为 `/batch-requests`，而不是 `/apisix/batch-requests`。

向暴露的批量请求端点发送一个由 GET 和 POST 请求组成的管道请求：

```
curl "http://127.0.0.1:9080/batch-requests" -X POST -d '

{

  "pipeline": [

    {

      "method": "GET",

      "path": "/anything"

    },

    {

      "method": "POST",

      "path": "/anything",

      "body": "a post request"

    }

  ]

}'
```

你应该会收到两个请求的响应，类似如下：

```
[

  {

    "reason": "OK",

    "body": "{\n  \"args\": {}, \n  \"data\": \"\", \n  \"files\": {}, \n  \"form\": {}, \n  \"headers\": {\n    \"Accept\": \"*/*\", \n    \"Host\": \"127.0.0.1\", \n    \"User-Agent\": \"curl/8.6.0\", \n    \"X-Amzn-Trace-Id\": \"Root=1-67b6e33b-5a30174f5534287928c54ca9\", \n    \"X-Forwarded-Host\": \"127.0.0.1\"\n  }, \n  \"json\": null, \n  \"method\": \"GET\", \n  \"origin\": \"192.168.107.1, 43.252.208.84\", \n  \"url\": \"http://127.0.0.1/anything\"\n}\n",

    "headers": {

      ...

    },

    "status": 200

  },

  {

    "reason": "OK",

    "body": "{\n  \"args\": {}, \n  \"data\": \"a post request\", \n  \"files\": {}, \n  \"form\": {}, \n  \"headers\": {\n    \"Accept\": \"*/*\", \n    \"Content-Length\": \"14\", \n    \"Host\": \"127.0.0.1\", \n    \"User-Agent\": \"curl/8.6.0\", \n    \"X-Amzn-Trace-Id\": \"Root=1-67b6e33b-0eddcec07f154dac0d77876f\", \n    \"X-Forwarded-Host\": \"127.0.0.1\"\n  }, \n  \"json\": null, \n  \"method\": \"POST\", \n  \"origin\": \"192.168.107.1, 43.252.208.84\", \n  \"url\": \"http://127.0.0.1/anything\"\n}\n",

    "headers": {

      ...

    },

    "status": 200

  }

]
```
