GraphQL API with TypeScript: Step-by-Step Practical Tutorial

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to GraphQL API with TypeScript



GraphQL is a query language for your API that allows clients to request only the data they actually need. Combined with TypeScript, you get strict typing, IDE autocompletion, and fewer errors at compile time. In this tutorial, we will build a full-fledged GraphQL API from scratch using TypeScript and Apollo Server.



This guide is suitable for developers familiar with the basics of JavaScript and Node.js. We will go from installing dependencies to testing the finished API.



1. Project Setup and Dependency Installation



First, let's create a new project and install the necessary packages. Open your terminal and run:



mkdir graphql-ts-tutorialcd graphql-ts-tutorialnpm init -y


Install TypeScript, Apollo Server, and GraphQL:



npm install apollo-server graphqlnpm install -D typescript @types/node ts-node nodemon


Create a tsconfig.json file for TypeScript configuration:



{  "compilerOptions": {    "target": "ES2020",    "module": "commonjs",    "rootDir": "./src",    "outDir": "./dist",    "strict": true,    "esModuleInterop": true,    "skipLibCheck": true  },  "include": ["src/**/*"]}


Create a src folder and a src/index.ts file — this will be the entry point for our application.



2. Creating the GraphQL Schema and TypeScript Types



In GraphQL, the schema defines the data types and operations available to the client. Let's create a simple schema for managing books.



File src/schema.ts:



import { gql } from 'apollo-server';

export const typeDefs = gql` type Book { id: ID! title: String! author: String! publishedYear: Int }

type Query { books: [Book] book(id: ID!): Book }

type Mutation { addBook(title: String!, author: String!, publishedYear: Int): Book deleteBook(id: ID!): Book }`;


Now let's define TypeScript interfaces for our data. Create src/types.ts:



export interface Book {  id: string;  title: string;  author: string;  publishedYear?: number;}


Note: TypeScript interfaces are needed for internal logic, while GraphQL types are for client-server interaction. They should be consistent.



3. Implementing Resolvers and the Server



Resolvers are functions that return data for each field of the schema. Let's create a file src/resolvers.ts with a simulated database:



import { Book } from './types';

let books: Book[] = [ { id: '1', title: 'War and Peace', author: 'Leo Tolstoy', publishedYear: 1869 }, { id: '2', title: 'Crime and Punishment', author: 'Fyodor Dostoevsky', publishedYear: 1866 },];

export const resolvers = { Query: { books: (): Book[] => books, book: (_: any, args: { id: string }): Book | undefined => { return books.find(book => book.id === args.id); }, }, Mutation: { addBook: (_: any, args: { title: string; author: string; publishedYear?: number }): Book => { const newBook: Book = { id: String(books.length + 1), title: args.title, author: args.author, publishedYear: args.publishedYear, }; books.push(newBook); return newBook; }, deleteBook: (_: any, args: { id: string }): Book | null => { const index = books.findIndex(book => book.id === args.id); if (index === -1) return null; const deletedBook = books.splice(index, 1)[0]; return deletedBook; }, },};


Now let's connect everything in the main file src/index.ts:



import { ApolloServer } from 'apollo-server';import { typeDefs } from './schema';import { r                

Blogs

Book Recommendations