Building CRUD API with NestJs - Write First API.
Tags: postgres, nestjs, node, tutorial
Published: 2021-10-08 18:53:11

###Part II

In [Part I](https://dev.to/rasoolk16/building-crud-api-with-nestjs-mikro-orm-and-postgres-43b5), we created nestjs project and created a database and then integrated Mikro-Orm. In this part we are going to create entities and start writing APIs.

We are first going to start with User module. We are going to structure our project like user folder will contain controller, service, repository, entities of it's own and after this module is completed we are going to export this module to our main module i.e. "app.module.ts file".
    First, let's create a "user" named folder in src directory. 

##Create an Entity
Now, let's create a folder "entities" which will contain all the entities related to user. 

{% gist https://gist.github.com/rskhan167/bcd062aecadf150fad93a386cd05bd07 %}

1. Here we used `@Entity` to define an entity. The entity contains many properties and these properties can be defined with either `@Property()`, `@ManyToOne()`, `@OneToMany()`, etc. These are known as decorators, to know more about these checkout out [Decorator Reference](https://mikro-orm.io/docs/decorators/).

2. There are also some optional properties like defining an entity property as nullable using `@Property({ nullable: true })` and also setting a default value for a property. Check out [Defining Entities] (https://mikro-orm.io/docs/defining-entities) to know more about how to define an entity and its properties.

3. We have also used 'class-validator' package which is used to validate an entity property itself. `@IsEmail()` decorator will check if the email is valid or not. We can add a lot these validation at entity creation level itself so that no improper data reaches the database.

Now let's create user repository. Create this file in the user directory itself.
```
//user.repository.ts
import { EntityRepository, Repository } from '@mikro-orm/core';
import { User } from './entities/user.entity';

@Repository(User)
export class UserRepository extends EntityRepository<User> {}
```

Now we need to run migration and apply the migration to create this user table in our database. 
    Run this command `npx mikro-orm migration:create` to create a new migration file. If any new entity is created or a change has been made to the existing entities, a new migration file will be generated. Then, `npx mikro-orm migration:up` command will apply the changes to the database.

Check out these other Mikroorm related commands:
```
npx mikro-orm migration:create   # Create new migration with current schema diff
npx mikro-orm migration:up       # Migrate up to the latest version
npx mikro-orm migration:down     # Migrate one step down
npx mikro-orm migration:list     # List all executed migrations
npx mikro-orm migration:pending  # List all pending migrations
```

{% gist https://gist.github.com/rskhan167/a2b1d170ee9eb630e6813526576a1ac2 %}
This is the migration file that is being generated. After applying  these changes to the database a new table will be created.

![User table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9xzwdqbtx4ocjo5thlf.png)

![User table columns](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lrb9j40znmuhrdfa4h5a.png)

##First API
Now that our table is created we can start writing APIs. We will create a controller and a service file. Controller file will handle all our APIs related to user and all the business logic will be written in service file.

###Controller
We will create a CreateUser API. This API will accept user details and then store it in our user table. First, we need to create a DTO(Data Transfer Object), in simple words DTOs are used to map objects to domain models. 
In user directory create "dtos" folder and inside it create "create-user.dto.ts" file.

{% gist https://gist.github.com/rskhan167/6615f1c4a7f418ac2752fefd4fc18643 %}

Here, we have defined all the properties needed to create a new user. As mentioned in previous post to validate a property we are using 'class-validator' library. 

Now we can create user controller file.
{% gist https://gist.github.com/rskhan167/b39459b364d89d2a7e0a90d15c98dc25 %}

We are injecting UserService here, where we will call database to perform CRUD operation. In controller, we just handle the incoming request and then send the response back to the client.

###Service
UserService is where we make the database call using ORM to store or retrieve the data. Services in Nestjs are known as Providers. Providers (services, repositories, helpers, etc.) can be injected as dependencies.

{% gist https://gist.github.com/rskhan167/c67a87668d455bb632bbfe61a0a0d0bd %}

1. As repositories are also providers these can be injected as dependency too and we inject UserRepository so that UserService can retrieve or store data in the database. 

2. We have a single method inside user service, which first checks if the a user with given email Id is already stored in database or not. Then, we create a User object using the constructor created in user entity. At last, we save the new user object in the database.

Before, we test our API as mentioned earlier, we need to import this user module in our main "app.module.ts" file. Just add the "UserModule" file in imports.

{% gist https://gist.github.com/rskhan167/e536d5406b83df5c89d906e6d1ca538b %}

##Test the API.
Run the "npm run start" or "npm run start:dev" command in the terminal to start the application.
For testing we are using Postman, you can download if you don't have it already or you can use postman online in your browser too.

We send a POST request to the `/api/user` endpoint:
![API testing using Postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0txoer99i3r4ilap3hqa.png)

After successful response we have our first entry in the database.
![Database](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/88boeclbnozvq6t7fgrx.png)

##Summary
In this tutorial, we created our first API and learned how to uses Mikro-Orm to store and retrieve data from database. And tested our API with postman.

Github Repository - https://github.com/rskhan167/movie-review

That's all for this part see you in the next one. Thanks for reading.
Please Like it and Share with your friends if you found it useful.