Add Request ID for API Requests
You may want to assign an ID for your API requests so that you can identify the request from external systems like querying the access log or the trace.
This guide will teach you how to add ID for your API requests with the help of the Request ID plugin.
Prepare the Environment
Deploy Apache APISIX
Please refer to How to Deploy Apache APISIX to learn how to deploy Apache APISIX and connect it to API7 Cloud. In this guide, we'll deploy an Apache APISIX instance on Docker.
Create Service and Route
We'll create a service with the following details in this guide.
- The service name is
request-id-app
. - The path prefix is
/v1
. - The HTTP Host is
request-id.httpbin.org
. - The upstream URL is
https://httpbin.org
.
Besides, we'll create a route inside the request-id-app
Service.
- The route name is
anything
. - The path is
/anything
(prefix match), and strip the path prefix. - It accepts all HTTP methods.
If you don't know how to configure a service and route, please refer to the Getting Started guides first
Add Request ID Plugin
Now let's add the Request ID plugin to the request-id-app
Service.
API7 Cloud will add an UUID for each request in this Service. We also include the ID in the response header.
Test
Now let's send a request to the anything
route.
curl http://127.0.0.1:9080/v1/anything -H 'Host: request-id.httpbin.org' -i
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 490
Connection: keep-alive
Date: Wed, 17 Aug 2022 08:16:10 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Server: APISIX/2.15.0
My-Request-ID: c93e7c59-7e98-4827-b945-8ef63cb6eb90
{
"args": {},
"data": "",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Host": "request-id.httpbin.org",
"My-Request-Id": "c93e7c59-7e98-4827-b945-8ef63cb6eb90",
"User-Agent": "curl/7.76.1",
"X-Amzn-Trace-Id": "Root=1-62fca3ca-69e1fd98029339a257b57276",
"X-Forwarded-Host": "request-id.httpbin.org"
},
"json": null,
"method": "GET",
"origin": "172.17.0.1, 61.241.66.251",
"url": "https://request-id.httpbin.org/anything"
}
As you can see from the response body, Apache APISIX takes the My-Request-ID
header when forwarding the request to the backend.
Also, since we enable the Include in Response
option, the My-Request-ID
header is shown in the response header.
Apache APISIX won't overwrite the request ID header if it already exists. Try to send another request with the header My-Request-ID: 123456
!