Open PortfolioOpen Portfolio.
โ† Back to Blog

How to Build a GraphQL API with TypeScript and Node.js

April 1, 2026at 2:00 PM UTCBy Pocket Portfolio Teamdevelopment
How to Build a GraphQL API with TypeScript and Node.js
#api#typescript#node.js#graphql#build

Problem

Building a robust API can be challenging, especially when dealing with complex data requirements and real-time updates. REST APIs can sometimes be too rigid or require multiple endpoints for varied data needs. GraphQL, on the other hand, offers a flexible approach to API development, allowing clients to query exactly the data they need. Combining GraphQL with TypeScript and Node.js can enhance type safety and developer productivity.

Solution with Code

To build a GraphQL API using TypeScript and Node.js, we will use the apollo-server and graphql libraries. Let's go through the steps:

  1. Initialize Your Node.js Project:

    mkdir graphql-api
    cd graphql-api
    npm init -y
    
  2. Install Required Packages:

    npm install apollo-server graphql
    npm install typescript @types/node ts-node --save-dev
    
  3. Setup TypeScript Configuration:

    Create a tsconfig.json file:

    {
      "compilerOptions": {
        "target": "ES2017",
        "module": "commonjs",
        "strict": true,
        "esModuleInterop": true,
        "outDir": "./dist"
      },
      "include": ["src/**/*"]
    }
    
  4. Define Your GraphQL Schema:

    In a new directory src, create a file schema.ts:

    import { gql } from 'apollo-server';
    
    export const typeDefs = gql`
      type Query {
        hello: String
      }
    `;
    
  5. Create Resolvers:

    In src, create a file resolvers.ts:

    export const resolvers = {
      Query: {
        hello: () => 'Hello world!',
      },
    };
    
  6. Setup Apollo Server:

    Create src/index.ts:

    import { ApolloServer } from 'apollo-server';
    import { typeDefs } from './schema';
    import { resolvers } from './resolvers';
    
    const server = new ApolloServer({ typeDefs, resolvers });
    
    server.listen().then(({ url }) => {
      console.log(`๐Ÿš€ Server ready at ${url}`);
    });
    
  7. Run Your Server:

    To start the server, run:

    npx ts-node src/index.ts
    

    You should see the server running and ready to accept queries.

Key Concepts

  • GraphQL: A query language for your API that allows clients to request only the data they need.
  • TypeScript: A superset of JavaScript that adds static typing, enhancing code quality and maintainability.
  • Apollo Server: A popular GraphQL server library for Node.js, which integrates seamlessly with TypeScript, offering tools for building a high-performance GraphQL API.

By following this guide, you set up a basic GraphQL server with a single query. You can expand this by adding more types, queries, and mutations according to your application's requirements.

How to Build a GraphQL API with TypeScript and Node.js | Open Portfolio Blog | Open Portfolio