Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Node.js GraphQL Basics
Node.js Intermediate FREE

GraphQL Basics

Lesson 1 of 17 Intermediate Interactive

GraphQL is a query language for APIs that lets clients request exactly the data they need.

Syntax

NODEJS
const { ApolloServer, gql } = require('apollo-server');

typedef type Query {
    users: [User]
    user(id: ID!): User
}

const resolvers = {
    Query: {
        users: () => db.users.findAll()
    }
};
GraphQL Schema and Resolvers
NODE
const { ApolloServer, gql } = require("apollo-server");

const typeDefs = gql`
    type User {
        id: ID!
        name: String!
        email: String!
    }

    type Query {
        users: [User]
        user(id: ID!): User
    }
`;

const resolvers = {
    Query: {
        users: () => [
            { id: "1", name: "Alice", email: "alice@example.com" }
        ],
        user: (_, { id }) =>
            ({ id, name: "Alice", email: "alice@example.com" })
    }
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen({ port: 4000 }).then(({ url }) => {
    console.log("GraphQL server ready at " + url);
});