Service

Description

A Service is an abstraction of an API (which can also be understood as a set of Route abstractions). It usually corresponds to an upstream service abstraction.

The relationship between Routes and a Service is usually N:1 as shown in the image below.

service-example

As shown, different Routes could be bound to the same Service. This reduces redundancy as these bounded Routes will have the same Upstream and Plugin configurations.

For more information about Service, please refer to Admin API Service object.

Examples

The following example creates a Service that enables the limit-count Plugin and then binds it to the Routes with the ids 100 and 101.

Service - 图2note

You can fetch the admin_key from config.yaml and save to an environment variable with the following command:

  1. admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 's/"//g')
  1. Create a Service.
  1. curl http://127.0.0.1:9180/apisix/admin/services/200 \
  2. -H "X-API-KEY: $admin_key" -X PUT -d '
  3. {
  4. "plugins": {
  5. "limit-count": {
  6. "count": 2,
  7. "time_window": 60,
  8. "rejected_code": 503,
  9. "key": "remote_addr"
  10. }
  11. },
  12. "upstream": {
  13. "type": "roundrobin",
  14. "nodes": {
  15. "127.0.0.1:1980": 1
  16. }
  17. }
  18. }'
  1. create new Route and reference the service by id 200

    1. curl http://127.0.0.1:9180/apisix/admin/routes/100 \
    2. -H "X-API-KEY: $admin_key" -X PUT -d '
    3. {
    4. "methods": ["GET"],
    5. "uri": "/index.html",
    6. "service_id": "200"
    7. }'
    1. curl http://127.0.0.1:9180/apisix/admin/routes/101 \
    2. -H "X-API-KEY: $admin_key" -X PUT -d '
    3. {
    4. "methods": ["GET"],
    5. "uri": "/foo/index.html",
    6. "service_id": "200"
    7. }'

We can also specify different Plugins or Upstream for the Routes than the ones defined in the Service. The example below creates a Route with a limit-count Plugin. This Route will continue to use the other configurations defined in the Service (here, the Upstream configuration).

  1. ```shell
  2. curl http://127.0.0.1:9180/apisix/admin/routes/102 \
  3. -H "X-API-KEY: $admin_key" -X PUT -d '
  4. {
  5. "uri": "/bar/index.html",
  6. "id": "102",
  7. "service_id": "200",
  8. "plugins": {
  9. "limit-count": {
  10. "count": 2000,
  11. "time_window": 60,
  12. "rejected_code": 503,
  13. "key": "remote_addr"
  14. }
  15. }
  16. }'
  17. ```
Service - 图3note

When a Route and a Service enable the same Plugin, the one defined in the Route is given the higher priority.