~/blog/create-service-and-route-kong-gateway
Published on

Creating Services and Routes in Kong Gateway

book2 minutes read

What is a service? A service is an entity for API services that defines our upstream service. A route is an endpoint to enter Kong, which will then direct to a specific service. For example, if we have an API server with an endpoint at http://localhost:3000/users, we can create a service named "users" and a route at http://localhost:8000/v1/users, which when accessed will route to http://localhost on port 3000 and the endpoint /users.

Okay, let's practice to understand it better!

Before proceeding, I am using the httpie tool to access Kong's admin endpoint.

Step 1: Create a Service

Create an API service for users located at http://localhost:3000/users

$ http :8001/services name=users url=http://localhost:3000/users

HTTP/1.1 201 Created
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 254
Content-Type: application/json; charset=utf-8
Date: Wed, 21 Nov 2018 06:36:55 GMT
Server: kong/0.14.1

{
    "connect_timeout": 60000,
    "created_at": 1542782215,
    "host": "localhost",
    "id": "626c2ffa-3034-41b1-a2f0-b506c0139b2c",
    "name": "users",
    "path": "/users",
    "port": 3000,
    "protocol": "http",
    "read_timeout": 60000,
    "retries": 5,
    "updated_at": 1542782215,
    "write_timeout": 60000
}

Step 2: Create a Route

Take the ID of the service you created to create a route.

$ http :8001/routes service:='{"id":"626c2ffa-3034-41b1-a2f0-b506c0139b2c"}' paths:='["/v1/users"]' methods:='["GET","POST","PATCH","PUT"]'

HTTP/1.1 201 Created
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 314
Content-Type: application/json; charset=utf-8
Date: Sun, 25 Nov 2018 10:51:59 GMT
Server: kong/0.14.1

{
    "created_at": 1543143119,
    "hosts": null,
    "id": "cdeeede8-75b8-44dc-9ee6-c8e808a680c8",
    "methods": [
        "GET",
        "POST",
        "PATCH",
        "PUT"
    ],
    "paths": [
        "/v1/users"
    ],
    "preserve_host": false,
    "protocols": [
        "http",
        "https"
    ],
    "regex_priority": 0,
    "service": {
        "id": "626c2ffa-3034-41b1-a2f0-b506c0139b2c"
    },
    "strip_path": true,
    "updated_at": 1543143119
}

Step 3: Check Configuration

After successfully creating the service and route, try accessing them.

$ http :8000/v1/users apikey:AisbenXBYMH7rFXhnOoaArn27lGrZOXb

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 53
Content-Type: application/json; charset=utf-8
Date: Sun, 25 Nov 2018 11:55:13 GMT
ETag: W/"35-D378nm5shd12kuL9ZrIOCXfvqaY"
Via: kong/0.14.1
X-Kong-Proxy-Latency: 0
X-Kong-Upstream-Latency: 30
X-Powered-By: Express

{
    "data": [],
    "message": "Request success",
    "status": true
}

In the example request above, I used an API key to access the API. For adding API key authentication in Kong, I have written a tutorial here.

That’s it, see ya~