Introduction
GraphQL has revolutionized how we interact with APIs, offering a more efficient and flexible alternative to RESTful services. NestJS, a progressive Node.js framework, not only streamlines backend development but also seamlessly integrates with GraphQL, allowing you to build powerful APIs with ease. This blog will guide you through creating a GraphQL API using NestJS, emphasizing clarity and best practices throughout.
Prerequisites
Before delving into the implementation, ensure you have the following set up:
- Basic knowledge of TypeScript and JavaScript
- Node.js and npm installed on your machine
- Familiarity with NestJS and GraphQL concepts
Setting up a New NestJS Project
Let’s kick things off by creating a new NestJS project. Open your terminal and run the following commands:
npm i -g @nestjs/cli nest new nest-graphql-api cd nest-graphql-api
This command installs the Nest CLI globally, creates a new NestJS project, and navigates into the project directory.
Installing GraphQL Dependencies
To enable GraphQL support in your NestJS application, install the necessary dependencies. Run the following:
npm install @nestjs/graphql graphql-tools graphql apollo-server-express
Here’s a quick breakdown of what these packages do:
@nestjs/graphql
: Provides the primary GraphQL integration for NestJS.graphql-tools
: A toolkit for building GraphQL APIs and schemas.graphql
: The core dependency that provides GraphQL functionalities.apollo-server-express
: An Apollo server package that serves GraphQL queries over HTTP.
Configuring GraphQL Module
Next, we'll set up the GraphQL module. Open app.module.ts
and import the GraphQLModule
like so:
import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { join } from 'path'; @Module({ imports: [ GraphQLModule.forRoot({ autoSchemaFile: join(process.cwd(), 'schema.gql'), }), ], }) export class AppModule {}
In this snippet, we configure the GraphQL module to generate a schema automatically, saving it to schema.gql
. The join
function helps build the absolute path where the schema file will be created.
Creating the First GraphQL Resolver
Now, let’s create our first resolver. A resolver is responsible for handling incoming queries. In our example, we'll create a simple CatsResolver
. First, generate a new module and a resolver:
nest generate module cats nest generate resolver cats
After running these commands, the folder structure will include a cats
module and resolver files.
Defining the Cat Entity
Before defining our resolver logic, let’s create a basic Cat
class. Create a new file cat.entity.ts
in the cats
directory:
export class Cat { id: number; name: string; age: number; }
This class represents a Cat entity. It's minimal for demonstration purposes, but you can expand it to include more properties later.
Implementing the Cats Resolver
Now we can add logic to our CatsResolver
. Open cats.resolver.ts
and edit it as follows:
import { Resolver, Query, Args } from '@nestjs/graphql'; import { Cat } from './cat.entity'; @Resolver(() => Cat) export class CatsResolver { private cats: Cat[] = [ { id: 1, name: 'Tommy', age: 3 }, { id: 2, name: 'Mittens', age: 2 }, ]; @Query(() => [Cat]) getCats(): Cat[] { return this.cats; } @Query(() => Cat, { nullable: true }) getCat(@Args('id') id: number): Cat | undefined { return this.cats.find((cat) => cat.id === id); } }
In this resolver, we define two queries:
- getCats: Returns a list of all cats.
- getCat: Retrieves a specific cat by its ID.
Creating GraphQL Schema
With the resolver in place, it’s important to define the GraphQL schema for our Cat
entity. Create a new file called cat.dto.ts
in the cats
directory:
import { Field, ObjectType } from '@nestjs/graphql'; @ObjectType() export class Cat { @Field() id: number; @Field() name: string; @Field() age: number; }
Here, we use decorators from @nestjs/graphql
to define our GraphQL schema. The @ObjectType
decorator marks the class as a GraphQL type, and @Field
is used to mark properties that should be part of the GraphQL schema.
Testing the GraphQL API
It's time to test our GraphQL endpoint! Start the development server:
npm run start:dev
Open your browser and navigate to http://localhost:3000/graphql
. You’ll be greeted by the Apollo Server interface where you can execute GraphQL queries. Here are a couple of example queries you might try:
- Fetch all cats:
query { getCats { id name age } }
- Fetch a specific cat:
query { getCat(id: 1) { name age } }
You should see the corresponding responses based on your queries. Feel free to play around, query additional properties, or even extend the functionality further!
Conclusion
Throughout this blog, we've navigated the essential steps in building a GraphQL API using NestJS, from setting up the project to creating schemas and resolvers. By leveraging the features of both NestJS and GraphQL, you've laid a solid foundation for building efficient and high-performing backend APIs.