/
mock-response-tyk-oas.md
438 lines (358 loc) · 19.6 KB
/
mock-response-tyk-oas.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
---
title: Using the Mock Response middleware with Tyk OAS APIs
date: 2024-01-31
description: "Using the Mock Response middleware with Tyk OAS APIs"
tags: ["mock response", "middleware", "per-endpoint", "Tyk OAS", "Tyk OAS API"]
---
The [Mock Response]({{< ref "product-stack/tyk-gateway/middleware/mock-response-middleware" >}}) middleware allows you to configure Tyk to return a response for an API endpoint without requiring an upstream service. This can be useful when creating a new API or making a development API available to an external team.
When working with Tyk OAS APIs, this middleware is executed at the end of the request processing chain immediately prior to the upstream proxy stage. Thus, any other request processing middleware - including authentication - will be run before the request reaches the mock response.
The middleware is configured in the [Tyk OAS API Definition]({{< ref "tyk-apis/tyk-gateway-api/oas/x-tyk-oas-doc#operation" >}}). You can do this via the Tyk Dashboard API or in the API Designer.
The Mock Response middleware has two modes of operation:
- with [manual mode](#manually-configuring-the-middleware-in-the-tyk-oas-api-definition), you can directly configure a response within the middleware in the Tyk extension (`x-tyk-api-gateway`) within the API definition. Tyk will give this response to all valid requests to the endpoint
- with [automatic mode](#automatically-configuring-the-middleware-from-the-openapi-document), Tyk will parse the [examples and schema]({{< ref "product-stack/tyk-gateway/middleware/mock-response-openapi" >}}) in the OpenAPI description and use this to generate responses automatically depending on the [content of the request](#working-with-multiple-mock-responses-for-an-endpoint)
If you're using the legacy Tyk Classic APIs, then check out the [Tyk Classic]({{< ref "product-stack/tyk-gateway/middleware/mock-response-tyk-classic" >}}) page.
## Manually configuring the middleware in the Tyk OAS API Definition
The design of the Tyk OAS API Definition takes advantage of the `operationId` defined in the OpenAPI Document that declares both the path and method for which the middleware should be added.
The mock response middleware (`mockResponse`) can be added to the `operations` section of the Tyk OAS Extension (`x-tyk-api-gateway`) in your Tyk OAS API Definition for the appropriate `operationId` (as configured in the `paths` section of your OpenAPI Document).
For basic operation, the `mockResponse` object has the following configuration:
- `enabled`: enable the middleware for the endpoint
- `code`: the HTTP status code to be provided with the response (this defaults to `200` if not set)
- `body`: the payload to be returned as the body of the response
- `headers`: the headers to inject with the response
For example:
```json {hl_lines=["39-49"],linenos=true, linenostart=1}
{
"components": {},
"info": {
"title": "example-mock-response1",
"version": "1.0.0"
},
"openapi": "3.0.3",
"paths": {
"/anything": {
"get": {
"operationId": "anythingget",
"responses": {
"200": {
"description": ""
}
}
}
}
},
"x-tyk-api-gateway": {
"info": {
"name": "example-mock-response1",
"state": {
"active": true
}
},
"upstream": {
"url": "http://httpbin.org/"
},
"server": {
"listenPath": {
"value": "/example-mock-response1/",
"strip": true
}
},
"middleware": {
"operations": {
"anythingget": {
"mockResponse": {
"enabled": true,
"code": 200,
"body": "This is the mock response body",
"headers": [
{
"name": "X-Example-Header",
"value": "foobar"
}
]
}
}
}
}
}
}
```
In this example the mock response middleware has been configured for requests to the `GET /example-mock-response1/anything` endpoint.
A call to `GET /example-mock-response1/anything` would return:
```
HTTP/1.1 200 OK
X-Example-Header: foobar
Content-Type: text/plain; charset=utf-8
This is the mock response body
```
The configuration above is a complete and valid Tyk OAS API Definition that you can import into Tyk to try out the mock response middleware.
## Automatically configuring the middleware from the OpenAPI Document
You can direct Tyk to configure the Mock Response middleware automatically from the examples and schema [defined]({{< ref "product-stack/tyk-gateway/middleware/mock-response-openapi" >}}) in the OpenAPI description.
The design of the Tyk OAS API Definition takes advantage of the `operationId` defined in the OpenAPI Document that declares both the path and method for which the middleware should be added. Endpoint `paths` entries (and the associated `operationId`) can contain wildcards in the form of any string bracketed by curly braces, for example `/status/{code}`. These wildcards are so they are human readable and do not translate to variable names. Under the hood, a wildcard translates to the “match everything” regex of: `(.*)`.
The mock response middleware (`mockResponse`) can be added to the `operations` section of the Tyk OAS Extension (`x-tyk-api-gateway`) in your Tyk OAS API Definition for the appropriate `operationId` (as configured in the `paths` section of your OpenAPI Document).
For basic operation, the `mockResponse` object has the following configuration:
- `enabled`: enable the middleware for the endpoint
- `fromOASExamples`: an object used to instruct Tyk Gateway to return a response from the OpenAPI description
The `fromOASExamples` object has the following configuration:
- `enabled`: enable the automatic configuration of mock response
- `code`: [optional] identifies which HTTP status code to be provided with the response (defaults to `200` if not set)
- `contentType`: [optional] identifies which response body type to use (defaults to `application/json` if not set)
- `exampleName`: [optional] the sample response to be returned from an `examples` list
The three optional fields (`code`, `contentType`, `exampleName`) are used to identify which sample response should be returned by the mock if multiple sample responses are declared in the OpenAPI description.
For example:
```json {hl_lines=["15-24", "29-33", "59-67"],linenos=true, linenostart=1}
{
"components": {},
"info": {
"title": "example-mock-response2",
"version": "1.0.0"
},
"openapi": "3.0.3",
"paths": {
"/anything": {
"get": {
"operationId": "anythingget",
"responses": {
"200": {
"content": {
"text/plain": {
"examples": {
"first-example": {
"value": "My favourite is pasta"
},
"second-example": {
"value": "My second favourite is pizza"
}
}
}
},
"description": ""
},
"300": {
"content": {
"text/plain": {
"example": "There's too much choice"
}
},
"description": ""
}
}
}
}
},
"x-tyk-api-gateway": {
"info": {
"name": "example-mock-response2",
"state": {
"active": true
}
},
"upstream": {
"url": "http://httpbin.org/"
},
"server": {
"listenPath": {
"value": "/example-mock-response2/",
"strip": true
}
},
"middleware": {
"operations": {
"anythingget": {
"mockResponse": {
"enabled": true,
"fromOASExamples": {
"enabled": true,
"code": 200,
"contentType": "text/plain",
"exampleName": "second-example"
}
}
}
}
}
}
}
```
In this example, the OpenAPI description declares three possible responses: two for HTTP 200 and one for HTTP 300. We have configured the Mock Response middleware to return the value defined for HTTP 200 (code) with `exampleName` set to "second-example".
If you make a call to `GET /example-mock-response2/anything` the response will be:
```bash
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Thu, 01 Feb 2024 12:31:50 GMT
Content-Length: 8
"My second favourite is pizza"
```
If you add `"code":300` in the `fromOASExamples` object, a call to `GET /example-mock-response2/anything` would instead respond as follows:
```bash
HTTP/1.1 300 Multiple Choices
Content-Type: text/plain
Date: Thu, 01 Feb 2024 12:35:45 GMT
Content-Length: 8
"There's too much choice"
```
{{< note success >}}
**Note**
If multiple `examples` are defined in the OpenAPI description but no default `exampleName` is set in the middleware configuration `fromOASExamples` Tyk will select randomly from the multiple `examples`. Yes, that means the response may change with every request. You can [control which response](#working-with-multiple-mock-responses-for-an-endpoint) will be returned using special headers in the request.
{{< /note >}}
The configuration above is a complete and valid Tyk OAS API Definition that you can import into Tyk to try out the mock response middleware.
## Working with multiple mock responses for an endpoint
When the mock response middleware in your Tyk OAS API is configured to return responses from the OpenAPI description within the API definition, you can invoke a specific response, overriding the defaults configured in the middleware, by providing specific headers in your request.
To invoke a non-default response from a mocked endpoint, you must add *one or more* special headers to the request:
- `Accept`: This standard HTTP header will override the response content type (e.g. `application/json`, `text/plain`)
- `X-Tyk-Accept-Example-Code`: This will select the HTTP response code for which to return the example response (e.g. `400`)
- `X-Tyk-Accept-Example-Name`: This identifies which example to select from an `examples` list
If an example response can’t be found for the configured `code`, `contentType` or `exampleName`, an HTTP 404 error will be returned to inform the client that there is no declared example for that configuration.
For example:
```json {hl_lines=["15-19", "22-39", "45-50", "53-55", "82-89"],linenos=true, linenostart=1}
{
"components": {},
"info": {
"title": "example-mock-response3",
"version": "1.0.0"
},
"openapi": "3.0.3",
"paths": {
"/anything": {
"get": {
"operationId": "anythingget",
"responses": {
"200": {
"headers": {
"X-Status": {
"schema": {
"type": "boolean"
}
}
},
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"lastName": {
"example": "Bar",
"type": "string"
},
"name": {
"example": "Foo",
"type": "string"
},
"id": {
"type": "integer"
}
}
}
}
},
"description": ""
},
"300": {
"headers": {
"X-Status": {
"schema": {
"type": "boolean",
"example": false
}
}
},
"content": {
"text/plain": {
"example": "Baz"
}
},
"description": ""
}
}
}
}
},
"x-tyk-api-gateway": {
"info": {
"name": "example-mock-response3",
"state": {
"active": true
}
},
"upstream": {
"url": "http://httpbin.org/"
},
"server": {
"listenPath": {
"value": "/example-mock-response3/",
"strip": true
}
},
"middleware": {
"operations": {
"anythingget": {
"mockResponse": {
"enabled": true,
"fromOASExamples": {
"enabled": true,
"code": 200,
"contentType": "application/json"
}
}
}
}
}
}
}
```
In this example, the OpenAPI document declares two possible responses: one for HTTP 200 and one for HTTP 300. We have configured the Mock Response middleware to return the value defined for HTTP 200 for which the body (content) is in JSON format and a custom header `X-Status` which will take the default value of `true`.
You can trigger the mock response for HTTP 300 by adding the following headers to your request:
- `X-Tyk-Accept-Example-Code`: 300
- `Accept`: text/plain
This would return a plain text body and the `X-Status` header set to `false`.
The configuration above is a complete and valid Tyk OAS API Definition that you can import into Tyk to try out the mock response middleware.
## Configuring the middleware in the API Designer
Adding a mock response to your API endpoints is easy when using the API Designer in the Tyk Dashboard, simply follow the steps appropriate to the configuration method you wish to use:
- [manual configuration](#manual-configuration) of the middleware config
- [automatic configuration](#automatic-configuration) from the OpenAPI description
### Manual configuration
##### Step 1: Add an endpoint
From the **API Designer** add an endpoint that matches the path and method to which you want to apply the middleware.
{{< img src="/img/dashboard/api-designer/tyk-oas-no-endpoints.png" alt="Tyk OAS API Designer showing no endpoints created" >}}
{{< img src="/img/dashboard/api-designer/tyk-oas-add-endpoint.png" alt="Adding an endpoint to an API using the Tyk OAS API Designer" >}}
{{< img src="/img/dashboard/api-designer/tyk-oas-no-middleware.png" alt="Tyk OAS API Designer showing no middleware enabled on endpoint" >}}
##### Step 2: Select the Mock Response middleware
Select **ADD MIDDLEWARE** and choose **Mock Response** middleware from the *Add Middleware* screen.
{{< img src="/img/dashboard/api-designer/tyk-oas-mock.png" alt="Adding the Mock Response middleware" >}}
##### Step 3: Configure the middleware
Select **Tyk Classic mock response**
{{< img src="/img/dashboard/api-designer/tyk-oas-mock-added.png" alt="Mock Response middleware added to endpoint - select the configuration method you require" >}}
This takes you to the middleware configuration screen where you can:
- choose the HTTP status code that you want Tyk Gateway to return
- select the content type
- add a description for your mock response
- define headers to be provided with the response
- define the body that will be returned in the response (note that this must be defined as a JSON schema)
{{< img src="/img/dashboard/api-designer/tyk-oas-mock-manual.png" alt="Configuring the mock response" >}}
Select **UPDATE MIDDLEWARE** to apply the change to the middleware configuration.
##### Step 4: Save the API
Select **SAVE API** to apply the changes to your API.
### Automatic configuration
##### Step 1: Import OpenAPI Document containing sample responses or schema
Import your OpenAPI Document (from file, URL or by pasting the JSON into the text editor) configuring the **upstream URL** and **listen path**, and selecting **Auto-generate middleware to deliver mock responses**.
Selecting this option will cause Tyk Dashboard to check for sample responses or schema in the OpenAPI description and will automatically add the Mock Response middleware for any endpoints that have suitable data.
{{< img src="/img/dashboard/api-designer/tyk-oas-mock-auto-options.png" alt="Configuring the OpenAPI document import to create Mock Responses" >}}
##### Step 2: Edit the Mock Response middleware
Select **EDIT** and then the **Mock Response** middleware from the **Endpoints** tab. This will take you to the Edit Middleware screen. Note that *Use mock response from Open API Specification* has been selected.
{{< img src="/img/dashboard/api-designer/tyk-oas-mock-auto-edit.png" alt="Editing the Mock Response middleware" >}}
##### Step 3: Configure the middleware
Tyk Dashboard will automatically have selected a valid HTTP response code from the drop-down. When you select a valid content-type for which a mock response is configured in the OpenAPI specification, the API Designer will display the associated response.
{{< img src="/img/dashboard/api-designer/tyk-oas-mock-auto-select.png" alt="Mock Response middleware automatically configured from OpenAPI description" >}}
Here you can edit the mock response:
- modify, add or delete Response Body examples (note that this must follow the selected content-type)
- choose a default Response Body example that will be provided (unless [overridden in the request]({{< ref "#working-with-multiple-mock-responses-for-an-endpoint" >}}))
- add a description for your mock response
- define headers to be provided with the response (note that these must be defined as a JSON schema)
- add a schema
You can create and edit mock responses for multiple HTTP status codes by choosing a different status code from the drop down.
Select **UPDATE MIDDLEWARE** to apply the change to the middleware configuration.
##### Step 4: Save the API
Select **SAVE API** to apply the changes to your API.
{{< note success >}}
**Note**
Modifying the automatically configured Mock Response middleware will update the OpenAPI description part of your Tyk OAS API definition, as the detail of the mock response is not set in the `x-tyk-api-gateway` extension but is automatically generated in response to the particular request received to the endpoint.
{{< /note >}}