3

API with NestJS #116. REST API versioning

 1 year ago
source link: https://wanago.io/2023/07/10/api-nestjs-rest-versioning/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

API with NestJS #116. REST API versioning

We value your privacy
We use cookies on our website. We would like to ask for your consent to store them on your device. We will not run optional cookies until you enable them. If you want to know more about how cookies work, please visit our Privacy Policy page.

API with NestJS #116. REST API versioning

NestJS

July 10, 2023
This entry is part 116 of 119 in the API with NestJS

The requirements of web applications constantly evolve, and so do the REST APIs they use. With the rise of the popularity of distributed systems and microservices, maintaining backward compatibility is increasingly important. Even if we maintain a monolithic architecture, there is a good chance that our frontend has a separate deployment pipeline. In this article, we implement REST API versioning in our NestJS application to handle updates gracefully and maintain a stable system.

Check out this repository to see the code from this article.

Versioning with NestJS

In one of the previous parts of this series, we changed the content property of the posts to paragraphs with a SQL migration.

ALTER TABLE "Post"
ADD COLUMN "paragraphs" TEXT[];
UPDATE "Post"
SET paragraphs = ARRAY[content];
ALTER TABLE "Post"
DROP COLUMN content;

If you want to know more about migrations with Prisma, check out API with NestJS #115. Database migrations with Prisma
If you use TypeORM, take a look at API with NestJS #69. Database migrations with TypeORM

Because of the above change, creating a new version of the endpoints related to posts makes sense. By implementing REST API versioning, we can maintain multiple versions of our controllers or individual routes. The most straightforward approach to API versioning is to include the version number in the URI of the request.

Screenshot-from-2023-07-09-20-54-35.png

Adding versioning to an existing project

To start working with versions, we need to modify our bootstrap function.

main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { VersioningType } from '@nestjs/common';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableVersioning({
    type: VersioningType.URI,
  await app.listen(3000);
bootstrap();

VersioningType.URI is the default value for the versioning type but we can provide it for the sake of readability.

Due to how we configured versioning with the app.enableVersioning method, our existing routes don’t include the version in the URL yet. Thanks to this approach, we are not introducing any breaking changes when starting to use versioning.

We now need to pass an additional argument to the @Controller() decorator that specifies the version.

posts.controller.ts
import { Controller } from '@nestjs/common';
import { PostsService } from './posts.service';
@Controller({
  version: '2',
  path: 'posts',
export default class PostsController {
  constructor(private readonly postsService: PostsService) {}
  // ...

Thanks to doing the above, we now have the /v2/ prefix in the URLs of endpoints related to posts.

To create a different version of the endpoints, we need to define a separate controller.

postsLegacy.controller.ts
import {
  ClassSerializerInterceptor,
  Controller,
  UseInterceptors,
  VERSION_NEUTRAL,
} from '@nestjs/common';
import { PostsService } from './posts.service';
@Controller({
  version: VERSION_NEUTRAL,
  path: 'posts',
@UseInterceptors(ClassSerializerInterceptor)
export default class PostsLegacyController {
  constructor(private readonly postsService: PostsService) {}
  // ...

By using VERSION_NEUTRAL as the version, NestJS uses the legacy controller when the version is not specified in the URL. Thanks to this approach, we can achieve backward compatibility if our project didn’t use versioning before.

We also need to remember about adding our new controller to the module.

posts.module.ts
import { Module } from '@nestjs/common';
import { PostsService } from './posts.service';
import PostsController from './posts.controller';
import { PrismaModule } from '../prisma/prisma.module';
import PostsLegacyController from './postsLegacy.controller';
@Module({
  imports: [PrismaModule],
  controllers: [PostsController, PostsLegacyController],
  providers: [PostsService],
export class PostsModule {}

Adjusting our controller to the new schema

We now need to deal with the legacy API handling data using the old format with content instead of paragraphs. In one of the previous parts of this series, we learned how to serialize the response of our controller through a custom interceptor when using Prisma. To use it, we need to create a DTO class first.

postsResponseLegacy.dto.ts
import { Exclude, Expose } from 'class-transformer';
export class PostsResponseLegacyDto {
  id: number;
  title: string;
  authorId: number;
  scheduledDate: Date | null;
  @Exclude({
    toPlainOnly: true,
  paragraphs: string[];
  @Expose()
  get content() {
    return this.paragraphs.join('\n');

Above, we hide the paragraphs property that came from our database and create the content. Thanks to this, we can serve our data in a legacy format, even though the database stores it differently.

postsLegacy.controller.ts
import {
  ClassSerializerInterceptor,
  Controller,
  Param,
  UseInterceptors,
  VERSION_NEUTRAL,
} from '@nestjs/common';
import { PostsService } from './posts.service';
import { FindOneParams } from '../utils/findOneParams';
import { TransformDataInterceptor } from '../utils/transformData.interceptor';
import { PostsResponseLegacyDto } from './dto/legacy/postsResponseLegacy.dto';
@Controller({
  version: VERSION_NEUTRAL,
  path: 'posts',
@UseInterceptors(ClassSerializerInterceptor)
export default class PostsLegacyController {
  constructor(private readonly postsService: PostsService) {}
  @Get(':id')
  @UseInterceptors(new TransformDataInterceptor(PostsResponseLegacyDto))
  getPostById(@Param() { id }: FindOneParams) {
    return this.postsService.getPostById(id);
  // ...

We can use a similar approach when creating entities by transforming the data posted by the user.

createPostLegacy.dto.ts
import {
  IsString,
  IsNotEmpty,
  IsNumber,
  IsOptional,
  IsISO8601,
} from 'class-validator';
import { Exclude } from 'class-transformer';
export class CreatePostLegacyDto {
  @IsString()
  @IsNotEmpty()
  title: string;
  @IsOptional()
  @IsNumber({}, { each: true })
  categoryIds?: number[];
  @IsISO8601({
    strict: true,
  @IsOptional()
  scheduledDate?: string;
  @Exclude({
    toPlainOnly: true,
  @IsString()
  @IsNotEmpty()
  content: string;
  get paragraphs() {
    return [this.content];

We now need to use the above class in our legacy controller.

postsLegacy.controller.ts
import {
  Body,
  ClassSerializerInterceptor,
  Controller,
  Post,
  UseGuards,
  UseInterceptors,
  VERSION_NEUTRAL,
} from '@nestjs/common';
import { PostsService } from './posts.service';
import JwtAuthenticationGuard from '../authentication/jwt-authentication.guard';
import RequestWithUser from '../authentication/requestWithUser.interface';
import { TransformDataInterceptor } from '../utils/transformData.interceptor';
import { PostsResponseLegacyDto } from './dto/legacy/postsResponseLegacy.dto';
import { CreatePostLegacyDto } from './dto/legacy/createPostLegacy.dto';
@Controller({
  version: VERSION_NEUTRAL,
  path: 'posts',
@UseInterceptors(ClassSerializerInterceptor)
export default class PostsLegacyController {
  constructor(private readonly postsService: PostsService) {}
  @Post()
  @UseGuards(JwtAuthenticationGuard)
  @UseInterceptors(new TransformDataInterceptor(PostsResponseLegacyDto))
  async createPost(
    @Body() post: CreatePostLegacyDto,
    @Req() req: RequestWithUser,
    return this.postsService.createPost(post, req.user);
  // ...

Designing the API with versioning in mind

There is a high probability that we will need to add versioning to our application at some point. Since that’s the case, we might as well design it with versioning in mind.

main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { VersioningType } from '@nestjs/common';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // ...
  app.enableVersioning({
    type: VersioningType.URI,
    defaultVersion: '1',
  await app.listen(3000);
bootstrap();

By supplying defaultVersion: '1' to the enableVersioning method, we add the /v1/ prefix to all our endpoints. Now, whenever we create a new version for one of the controllers, the change in the URL feels more natural. For example, /v1/posts becomes /v2/posts.

The above also requires us to adjust our legacy controller. Instead of VERSION_NEUTRAL, we specify 1 as the version.

postLegacy.controller.ts
import {
  ClassSerializerInterceptor,
  Controller,
  UseInterceptors,
} from '@nestjs/common';
import { PostsService } from './posts.service';
@Controller({
  version: '1',
  path: 'posts',
@UseInterceptors(ClassSerializerInterceptor)
export default class PostsLegacyController {
  constructor(private readonly postsService: PostsService) {}
  // ...

Other types of versioning

While the URI versioning is default and very popular, NestJS also supports other types of versioning.

Header versioning

The header versioning uses a custom header to specify the version of the controller used to handle a particular request.

app.enableVersioning({
  type: VersioningType.HEADER,
  header: 'Api-Version',

Media type versioning

The Accept request header indicates which content types the API client can understand. A good example is Accept: application/json.

With media-type versioning, we use the Accept header to specify the version, such as Accept: application/json;v=2.

app.enableVersioning({
  type: VersioningType.MEDIA_TYPE,
  key: 'v=',

Custom versioning type

If none of the above solutions fit our API, we can implement a custom versioning.

import { AppModule } from './app.module';
import { VersioningType } from '@nestjs/common';
import { isRecord } from './utils/isRecord';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableVersioning({
    type: VersioningType.CUSTOM,
    extractor: (request: unknown) => {
      if (isRecord(request) && isRecord(request.query)) {
        return String(request.query.version);
      return '1';
  // ...
  await app.listen(3000);
bootstrap();

Unfortunately, the type of the request is unknown and we need to use type assertions.

Summary

In this article, we’ve gone through the idea of REST API versioning. We used URI versioning to create a legacy version of our controller and transformed data to match the previous format our API was using. We also learned about other versioning types, such as header and media-type versioning.

API versioning can be a handy tool to preserve backward compatibility. However, we need to remember to remove the older versions of our API when they are not required anymore to avoid cluttering our codebase.

Series Navigation<< API with NestJS #115. Database migrations with PrismaAPI with NestJS #117. CORS – Cross-Origin Resource Sharing >>
Subscribe
guest
Label
0 Comments

wpDiscuz


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK