How to create GraphQL API in Nest JS? Step by Step guidelines!
Published: 2024-06-04 05:18:47

Creating a GraphQL API in NestJS involves several steps. Here's a step-by-step theoretical guide:

### Step 1: Setup a New NestJS Project
1. **Install Nest CLI**:
   ```bash
   npm install -g @nestjs/cli
   ```
2. **Create a New Project**:
   ```bash
   nest new project-name
   ```
3. **Navigate to the Project Directory**:
   ```bash
   cd project-name
   ```

### Step 2: Install GraphQL and Apollo Server
1. **Install Required Packages**:
   ```bash
   npm install @nestjs/graphql graphql apollo-server-express
   ```

### Step 3: Configure GraphQL Module
1. **Create a GraphQL Module Configuration**:
   Open `src/app.module.ts` and configure the GraphQL module:
   ```typescript
   import { Module } from '@nestjs/common';
   import { GraphQLModule } from '@nestjs/graphql';
   import { join } from 'path';

   @Module({
     imports: [
       GraphQLModule.forRoot({
         autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
       }),
     ],
   })
   export class AppModule {}
   ```

### Step 4: Create a Resolver
1. **Generate a Resolver**:
   Use the Nest CLI to generate a resolver:
   ```bash
   nest g resolver user
   ```

2. **Define Resolver Logic**:
   Open `src/user/user.resolver.ts` and define the resolver logic:
   ```typescript
   import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
   import { UserService } from './user.service';
   import { User } from './user.entity';
   import { CreateUserInput } from './dto/create-user.input';

   @Resolver(of => User)
   export class UserResolver {
     constructor(private readonly userService: UserService) {}

     @Query(returns => [User])
     async users() {
       return this.userService.findAll();
     }

     @Mutation(returns => User)
     async createUser(@Args('createUserInput') createUserInput: CreateUserInput) {
       return this.userService.create(createUserInput);
     }
   }
   ```

### Step 5: Create a Service
1. **Generate a Service**:
   Use the Nest CLI to generate a service:
   ```bash
   nest g service user
   ```

2. **Implement Service Logic**:
   Open `src/user/user.service.ts` and implement the service logic:
   ```typescript
   import { Injectable } from '@nestjs/common';
   import { User } from './user.entity';
   import { CreateUserInput } from './dto/create-user.input';

   @Injectable()
   export class UserService {
     private users: User[] = [];

     findAll(): User[] {
       return this.users;
     }

     create(createUserInput: CreateUserInput): User {
       const user = { ...createUserInput, id: Date.now().toString() };
       this.users.push(user);
       return user;
     }
   }
   ```

### Step 6: Define GraphQL Schema and DTOs
1. **Create GraphQL Schema and DTOs**:
   Create the `src/user/user.entity.ts`:
   ```typescript
   import { ObjectType, Field, ID } from '@nestjs/graphql';

   @ObjectType()
   export class User {
     @Field(type => ID)
     id: string;

     @Field()
     name: string;

     @Field()
     email: string;
   }
   ```

   Create the `src/user/dto/create-user.input.ts`:
   ```typescript
   import { InputType, Field } from '@nestjs/graphql';

   @InputType()
   export class CreateUserInput {
     @Field()
     name: string;

     @Field()
     email: string;
   }
   ```

### Step 7: Update Module
1. **Update the Module to include Resolver and Service**:
   Open `src/user/user.module.ts` and update it:
   ```typescript
   import { Module } from '@nestjs/common';
   import { UserService } from './user.service';
   import { UserResolver } from './user.resolver';

   @Module({
     providers: [UserService, UserResolver],
   })
   export class UserModule {}
   ```

### Step 8: Integrate the User Module
1. **Integrate the User Module into the App Module**:
   Open `src/app.module.ts` and update it:
   ```typescript
   import { Module } from '@nestjs/common';
   import { GraphQLModule } from '@nestjs/graphql';
   import { join } from 'path';
   import { UserModule } from './user/user.module';

   @Module({
     imports: [
       GraphQLModule.forRoot({
         autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
       }),
       UserModule,
     ],
   })
   export class AppModule {}
   ```

### Step 9: Run the Application
1. **Start the NestJS Application**:
   ```bash
   npm run start:dev
   ```

### Step 10: Test the GraphQL API
1. **Access the GraphQL Playground**:
   Navigate to `http://localhost:3000/graphql` to access the GraphQL playground and test your API by running queries and mutations.

This guide provides a foundational approach to creating a GraphQL API in NestJS. You can further expand and customize it based on your application's requirements.

Disclaimer: This content in generated by AI.