CRUD functions

How to generate CRUD API endpoints with NestJS

Setting up CRUD API endpoints with NestJS is easy. Being a "batteries included" framework Nest.js allows us to create our CRUD API with one simple command. In this tutorial, we will be using the NestJS CLI to generate a new project and then we will generate our API endpoints.

        
    npm i -g @nestjs/cli
    nest new swagger-demo
        
      

First, we need to enter our swagger-demo directory. Then we will use the NestJS CLI to generate our resource.

        
    cd swagger-demo
    nest g resource
        
      

Here you will be prompted to enter the name of your resource. I will be using "user" as my resource name. You can use any name you want just type it in when prompted then press enter. Afterwards Nest will ask you to select the type of API you want to generate. I will be selecting REST-API. Nest will ask you if you would like to generate the CRUD entry points. Type in a "Y" for yes and press enter.

Done!

Just like that we have generated our CRUD API endpoints. As we can see Nest not only generated our API endpoints but it also created a controller, service, and a module for us. It also generated a DTO for us. A DTO is a data transfer object. It is used to transfer data between processes. We also now have an Entity for our user. An entity is a class that represents a table in a database. If you check your app.module.ts file you will see that the user module has been automatically imported for us. Check out my tutorial on how to implement Swagger API documentation with NestJS to learn how to document and view the endpoints you just created. Feel free to reach out to me on Twitter @GmoMedel if you have any questions.

Swagger API

My Blog