Prevent default response code in Swagger/OpenAPI definition with NestJS - swagger

What I'm trying
I'm implementing a DELETE route using NestJS.
Since the route is only ever supposed to return a HTTP 204 No Content on successful deletion, utilizing the #nestjs/swagger decorators, I've annotated it as follows:
#ApiParam({
name: 'id',
required: true,
type: 'string',
example: 'abc123',
})
#ApiNoContentResponse({
description: 'All items for the given id have been deleted',
})
#Delete('/accounts/:id/items')
async deleteItems(
#Param('id') id: string,
) {
// do stuff
}
Stack
#nestjs/cli: 9.1.6
#nestjs/common: 9.1.6
#nestjs/core: 9.1.6
#nestjs/platform-express: 9.1.6
#nestjs/swagger: 6.1.2
nest-cli.json
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "#nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"plugins": [
"#nestjs/swagger/plugin"
]
}
}
Question
How can I prevent this (default?) response from being generated?
What happens
When running the server with npm run start:dev, the swagger description for my route is created. Although I've not explicitly defined it, the description now contains an entry for HTTP 200 in the Response section of the route. The entry contains no description and no indicator that it's not explicitly defined.
What I expected to happen
When running the server with npm run start:dev, the swagger description for my route is created. The description only contains and entry for HTTP 204 in the Response section of the route.
What I've tried
Explicitly defined an #ApiOkResponse:
// they all have no effect
#ApiOkResponse()
// OR
#ApiOkResponse({})
// OR
#ApiOkResponse({ status: 204 })
Defined an #ApiDefaultResponse:
// they all create a response 'default' with no description
#ApiDefaultResponse()
// OR
#ApiDefaultResponse({})
// OR
#ApiDefaultResponse({ status: 204 })

You can just add #HttpCode(204) as an annotation to your code. 200 is added by default, because this is the default response status code for DELETE requests.This default behavior would be overwritten with the annotation mentioned above.
More information about the status codes can be found here: https://docs.nestjs.com/controllers

Related

Swagger UI does not show file upload option (and not only that) in OpenAPI 3.0.3 Request Body info

I was trying to add a file upload option for a POST request in Swagger UI by following the documentation.
The problem is this:
As you can see, Swagger UI does not render anything, neither for textual inputs nor for file inputs.
I tried to search on SO other answers about this but nothing.
This is the request body that I defined for the requestBody parameter of the path:
CreateTicketMessagePayload:
description: |-
Request multipart body required to proceed in the ticket message creation processes.
**Object part**:
```
{
"message": "Textual content of the message",
"private": "Flag that indicates the message is visible just for technicians"
}
```
**File part**:
"attachment": Message attachment file.
content:
multipart/form-data:
schema:
type: object
properties:
message:
type: string
example: This is a message
private:
type: boolean
example: false
attachment:
type: string
format: binary
What am I doing wrong?
In case of multipart/form-data requests, Swagger UI shows the inputs after you click "Try it out".
There's an existing enhancement request to display the inputs by default:
Display static documentation information for multipart properties in OpenAPI 3.0 files

How to format code blocks in descriptions in Swagger UI 3.x?

I would like to put a Markdown code block in the description of my API but the Swagger UI seems to be reading as though it was a single line code snippet. I currently have:
description: |
This API was created to allow interaction with the Image Status Database (ISD)
## Requests
## Responses
In the case of a successful response, you will always receive a `data` key
that contains your data.
```
{
"meta": {
"code": 200
},
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}
```
This gets displayed as:
The Swagger Editor, however, displays the proper code block:
Is this not supported by the Swagger UI?
The code block formatting issue was fixed in Swagger UI 3.22.0 and Swagger Editor 3.6.26. Code blocks are displayed properly in these versions:
Note the line break between "a data key" and "that contains" in the text - it is caused by the | literal block style, which preserves the line breaks in YAML multi-line strings. To avoid that line break you can either 1) remove it in your YAML, or 2) use the > folded style and also indent the code block (to prevent it from being folded), as shown below:
description: >
This API was created to allow interaction with the Image Status Database (ISD)
## Requests
## Responses
In the case of a successful response, you will always receive a `data` key
that contains your data.
```
{
"meta": {
"code": 200
},
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}
```

SwaggerUI: Path shows "Default". How can I change?

I downloaded sample server program from http://editor.swagger.io. (Swagger Petstore (Simple), NodeJS)
Then I deployed into my server but the path is showed "Default". How can I change it?
This sample shows the name of paths. This is what I want to do it. http://petstore.swagger.io/#/
package.json
"dependencies": {
"connect": "^3.2.0",
"js-yaml": "^3.3.0",
"swagger-tools": "0.9.*"
}
=============================
Update
This may be related. How to change Swagger-UI "Default" Path
I'm not sure how JSON file is necessary. I'm using yaml. I may be choose .json or .yaml.
And also I'm wondering this is related to my issue..
{
schemaValidationMessages: [
{
level: "error",
message: "Can't read from file http://xxxxx/api-docs"
}
]
}
The grouping is done by the use of tags. Just tag each operation with a string array like such:
get:
tags:
- Admin Operations
parameters: []
The description for tags is defined in a top-level tags object:
tags:
- name: Admin Functions
description: These are only for special users!
And this will show the description in the top-level

"additional properties" error in Survey Monkey API call

I'm trying to use the create_flow endpoint to the Survey Monkey API. It is sending back a status 3 message with the following error:
additional properties not defined by 'properties' are not allowed in field '_data'
I'm able to do successfully use all other API endpoints and have a valid API key and durable OAuth token.
Here's an example JSON body that I'm sending to: https://api.surveymonkey.net/v2/batch/create_flow?api_key=apikeyhere
{
"survey": {
"template_id": "566",
"survey_title": "test1",
"collector": {
"type": "email",
"name": "collector1",
"recipients": [
{
"email": "email#example.com"
}
]
},
"email_message": {
"reply_email": "myemail#example.com",
"subject": "this is a test"
}
}
Note: JSON formatting here is being generated automatically using RJSONIO
Any ideas what might be causing the error? It seems like all fields are correctly named and where they're supposed to be, so I'm not sure what the problem is.
It's a bad error message unfortunately - it's a known issue. It means you are providing extra keys that are not part of the create_flow schema.
The issue here is that the "email_message" and "collector" keys have been nested inside of "survey", instead of being in the main JSON body like the "survey" key. Move them out a level and it should work.

422 error when creating a ticket in Zendesk

I am developping an app in ASP.NET MVC5 using Zendesk_v2 (uploaded using a nuget package). I have admin rights for subdomain easynext.zendesk.com.
Here is my code for creating a ticket:
private static string requestUri = "https://easynext.zendesk.com/api/v2/tickets.json";
private static string _username = "gbalasel#easynext.be";
private static string _password = "MYPASSWORD";
private static ZendeskApi apiZendesk = new ZendeskApi(requestUri, _username, _password, "");
private void CréerTicketZendesk() {
var myTicket = apiZendesk.Tickets.CreateTicket(new Ticket()
{
Subject = "test ticket",
Priority = TicketPriorities.Low
});
}
This code sends me a 422 Unprocessable Entity error.
I have also made a test account for a client in Zendesk and the method works fine, the ticket is created in Zendesk and I also receive it in my email account.
Status 422 is most likely caused by a semantic error on your part. In my experience, ZD can return 422 most often in two situations:
When trying to PUT an update to a ticket whose status is closed. In that case, you need to create a new ticket or a follow-up ticket, if possible.
Setting an invalid value on some attribute of the ticket object or sub-object of the ticket. This can be particularly tedious to debug, as the ZD response doesn't usually tell you which attribute has an invalid value. You should check all the integer values that you are setting on the ticket. E.g., I've been burned by using the Group IDs from my production Zendesk while developing on the Sandbox System (they most likely have entirely different IDs for everything, including custom fields, groups, users, etc.).
If you are creating new tickets via POST, be sure to check all the values you are setting, as per my second bullet point above.
This telling you that you have not formed a request that it can handle; the destination script exists (otherwise you'd see a 404), the request is being handled (otherwise you'd get a 400 error) and it's been encoded correctly (or you'd get a 415 error) but the actual instruction can't be carried out.
take a look on this for more info.
Error List
just to add to the solution if anyone encounters the same problem.
requester_id is mandatory while posting the ticket json.
A sample ticket json -
{
"ticket": {
"subject": "My printer is on fire!",
"requester_id": 123,
"assignee_id": 456,
"type": "incident",
"subject": "Help, my printer is on fire!",
"description": "The fire is very colorful.",
"priority": "High",
"status": "open",
"custom_fields": [
{
"id": 111, // custom field ID
"value": "500.23"
}
]
}
}
Thanks
Yeah I run today to the same problem and solved it. The problem is that you need a comment and body part inside the ticket structure.
So this is how it could look like (in PHP):
$ticket = [
'group_id' => '35135',
'title' => 'Title',
'subject' => 'Subject',
'type' => 'ticket',
'comment' => ['body' => 'Comment text.'],
'priority' => 'normal',
'ticket_form_id' => '454524',
'custom_fields' => [
'51325351' => 'test',
],
];
Take a look on here:
https://developer.zendesk.com/rest_api/docs/core/tickets
I had an issue with the Zendesk API throwing a 422 when I was attempting to create a ticket. All parameters were correct, the problem was that the assignee for which the ticket was created for did not belong to the group.
I found this error by looking at the request response by using FIDDLER.
Adding this here in case someone else runs into this issue. For me the ticket formatting was correct, but the requester was suspended:
Error Result:
{
"error": "RecordInvalid",
"description": "Record validation errors",
"details": {
"requester": [{
"description": "Requester: jkraft is suspended."
}]
}
}
Follow these instructions to unsuspend a user: https://support.zendesk.com/hc/en-us/articles/4408835668634-How-do-I-unsuspend-access-for-a-user-
I hope this is helpful to tell whether or not you are receiving the HTTP 422 because the ticket was already closed or if its because you were trying to do something like edit a field with invald params:
If you log the response object from zendesk for the failed http 422, you can look at the response object and check its configs. In my example it was:
response: {
status: 422,
statusText: 'Unprocessable Entity',
headers: {
date: 'Wed, 01 Feb 2023 17:48:00 GMT',
'content-type': 'application/json; charset=utf-8',
'content-length': '145',
connection: 'close',
'x-zendesk-api-version': 'v2',
'x-zendesk-application-version': 'v15375',
'x-frame-options': 'SAMEORIGIN',
'zendesk-rate-limit-tickets-update': 'total=100; remaining=99; resets=60',
'x-rate-limit': '700',
'rate-limit': '700',
'x-rate-limit-remaining': '699',
'rate-limit-remaining': '699',
'rate-limit-reset': '60',
'strict-transport-security': 'max-age=31536000;',
'cache-control': 'no-cache',
'x-zendesk-origin-server': 'classic-app-server-5b7bb5f96b-2bngr',
'set-cookie': [Array],
'x-request-id': '792c83f6384a5f9a-SMF, 792c83f6384a5f9a-SMF',
'x-runtime': '0.086818',
'x-zendesk-zorg': 'yes',
'cf-cache-status': 'DYNAMIC',
'report-to': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=mwQlS2H5vr2L4HJeTbyCvhjJbRJIwwhO%2FjJFw1z5cpIkak9Oke5GtqcaWsrzIF9gnYxTnkiPAFpkBgprHoXcr2yi%2FvA7grLEoQvXeHhsSmzOnu2LslqRDbzYeeMhRRtQwIrE0uLhrZJxTzlo%2FIfcKZ4%3D"}],"group":"cf-nel","max_age":604800}',
nel: '{"success_fraction":0.01,"report_to":"cf-nel","max_age":604800}',
server: 'cloudflare',
'cf-ray': '792c83f6384a5f9a-SMF'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 10000,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
baseURL: 'https://***.zendesk.com/',
method: 'put',
url: '/api/v2/tickets/69519.json',
data: '{"ticket":{"status":"open","comment":{"html_body":"Follow-up Notes: \\n<p><br></p>","public":false}}}'
},
If you will notice, the 'url' and 'data' properties of the config object in my case proved I was hitting the correct api endpoint and I was also providing the correctly formatted payload. This led me to pull the tickets status and confirm it was closed, which was the source reason for the 422 response.

Resources