Careers in tech are changing rapidly. Check out the latest AI job postings on Authentic Jobs!
ads via Carbon
Operations
In OpenAPI terms, paths are endpoints (resources), such as
/users
or
/reports/summary
, that your API exposes, and operations are the HTTP methods used to manipulate these paths, such as
GET
,
POST
or
DELETE
.
To define a custom HTTP response, use the
@ApiResponse()
decorator.
@Post()@ApiResponse({ status:201, description:'The record has been successfully created.'})@ApiResponse({ status:403, description:'Forbidden.'})asynccreate(@Body() createCatDto: CreateCatDto){this.catsService.create(createCatDto);
Nest provides a set of short-hand
API response
decorators that inherit from the
@ApiResponse
decorator:
@ApiOkResponse()
@ApiCreatedResponse()
@ApiAcceptedResponse()
@ApiNoContentResponse()
@ApiMovedPermanentlyResponse()
@ApiFoundResponse()
@ApiBadRequestResponse()
@ApiUnauthorizedResponse()
@ApiNotFoundResponse()
@ApiForbiddenResponse()
@ApiMethodNotAllowedResponse()
@ApiNotAcceptableResponse()
@ApiRequestTimeoutResponse()
@ApiConflictResponse()
@ApiPreconditionFailedResponse()
@ApiTooManyRequestsResponse()
@ApiGoneResponse()
@ApiPayloadTooLargeResponse()
@ApiUnsupportedMediaTypeResponse()
@ApiUnprocessableEntityResponse()
@ApiInternalServerErrorResponse()
@ApiNotImplementedResponse()
@ApiBadGatewayResponse()
@ApiServiceUnavailableResponse()
@ApiGatewayTimeoutResponse()
@ApiDefaultResponse()
@Post()@ApiCreatedResponse({ description:'The record has been successfully created.'})@ApiForbiddenResponse({ description:'Forbidden.'})asynccreate(@Body() createCatDto: CreateCatDto){this.catsService.create(createCatDto);
To specify a return model for a request, we must create a class and annotate all properties with the
@ApiProperty()
decorator.
Then the
Cat
model can be used in combination with the
type
property of the response decorator.
@ApiTags('cats')@Controller('cats')exportclassCatsController{@Post()@ApiCreatedResponse({
description:'The record has been successfully created.',
type: Cat,asynccreate(@Body() createCatDto: CreateCatDto):Promise<Cat>{returnthis.catsService.create(createCatDto);
Let's open the browser and verify the generated
Cat
model:
Instead of defining responses for each endpoint or controller individually, you can define a global response for all endpoints using the
DocumentBuilder
class. This approach is useful when you want to define a global response for all endpoints in your application (e.g., for errors like
401 Unauthorized
or
500 Internal Server Error
).
const config =newDocumentBuilder().addGlobalResponse({
status:500,
description:'Internal server error',// other configurations.build();
You can enable file upload for a specific method with the
@ApiBody
decorator together with
@ApiConsumes()
. Here's a full example using the
File Upload
technique:
@UseInterceptors(FileInterceptor('file'))@ApiConsumes('multipart/form-data')@ApiBody({
description:'List of cats',
type: FileUploadDto,uploadFile(@UploadedFile() file: Express.Multer.File){}
We skip decorating
results
as we will be providing a raw definition for it later. Now, let's define another DTO and name it, for example,
CatDto
, as follows:
In this example, we specify that the response will have allOf
PaginatedDto
and the
results
property will be of type
Array<CatDto>
.
getSchemaPath()
function that returns the OpenAPI Schema path from within the OpenAPI Spec File for a given model.
allOf
is a concept that OAS 3 provides to cover various Inheritance related use-cases.
Lastly, since
PaginatedDto
is not directly referenced by any controller, the
SwaggerModule
will not be able to generate a corresponding model definition just yet. In this case, we must add it as an
Extra Model
. For example, we can use the
@ApiExtraModels()
decorator on the controller level, as follows:
Hint
Type<any>
interface and
applyDecorators
function are imported from the
@nestjs/common
package.
To ensure that
SwaggerModule
will generate a definition for our model, we must add it as an extra model, like we did earlier with the
PaginatedDto
in the controller.
With this in place, we can use the custom
@ApiPaginatedResponse()
decorator on our endpoint:
For client generation tools, this approach poses an ambiguity in how the
PaginatedResponse<TModel>
is being generated for the client. The following snippet is an example of a client generator result for the above
GET /
endpoint.