Labs ICT
Pro Login

Getting Started with GraphQL

Getting Started with GraphQL

Let's set up a GraphQL server from scratch. We'll use Node.js with Apollo Server, which is the most popular GraphQL server implementation.

First, create a new project and install the dependencies:

mkdir graphql-demo
cd graphql-demo
npm init -y
npm install @apollo/server graphql

Your First Server

Create a file called index.js and add the following code:

const { ApolloServer } = require('@apollo/server');
const { startStandaloneServer } = require('@apollo/server/standalone');

const typeDefs = `
  type Query {
    hello: String!
    currentTime: String!
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello, GraphQL!',
    currentTime: () => new Date().toISOString(),
  },
};

async function startServer() {
  const server = new ApolloServer({ typeDefs, resolvers });
  const { url } = await startStandaloneServer(server, { listen: { port: 4000 } });
  console.log(`Server ready at ${url}`);
}

startServer();

Run the server with node index.js and open your browser to http://localhost:4000. You'll see Apollo Sandbox where you can write queries.

Writing Your First Query

In the Apollo Sandbox, type this query:

query {
  hello
  currentTime
}

You'll get back a response like this:

{
  "data": {
    "hello": "Hello, GraphQL!",
    "currentTime": "2024-01-15T10:30:00.000Z"
  }
}

Congratulations! You just made your first GraphQL query. The server returned exactly the data you asked for.

Adding More Types

Let's make things more interesting by adding a User type:

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

  type Query {
    hello: String!
    user(id: ID!): User
  }
`;

const users = [
  { id: '1', name: 'Alice', email: 'alice@example.com' },
  { id: '2', name: 'Bob', email: 'bob@example.com' },
];

const resolvers = {
  Query: {
    hello: () => 'Hello, GraphQL!',
    user: (parent, args) => users.find(u => u.id === args.id),
  },
};

Now you can query for a specific user: query { user(id: "1") { name email } }

What's Next

You now have a working GraphQL server! In the next sections, we'll dive deeper into schemas, types, queries, and mutations. We'll also look at how to connect to a database and build more complex APIs.

Remember, GraphQL is all about asking for exactly what you need. Practice writing different queries and see how the response changes based on what fields you request.