Setting up a server allows GraphQL to receive and respond to requests from clients. This makes it possible to ask for exactly the data you want, and get it quickly.
0
0
Why server setup enables GraphQL
Introduction
You want a single place to get data from many sources like databases or APIs.
You want clients to ask for only the data they need, not too much or too little.
You want to update or add data easily through one system.
You want to improve app speed by reducing extra data sent over the network.
You want to handle different types of devices (phones, web) with one data service.
Syntax
GraphQL
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'Hello world!' } }; const server = new ApolloServer({ typeDefs, resolvers }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
This example uses Apollo Server, a popular GraphQL server library.
typeDefs define the data types and queries clients can ask.
Examples
This shows a server setup with no queries or data yet. It runs but does not serve data.
GraphQL
const { ApolloServer, gql } = require('apollo-server'); // Empty schema example const typeDefs = gql``; const resolvers = {}; const server = new ApolloServer({ typeDefs, resolvers }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
This server lets clients ask for a greeting with a name or default to 'Guest'.
GraphQL
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type Query { greet(name: String): String } `; const resolvers = { Query: { greet: (_, { name }) => `Hello, ${name || 'Guest'}!` } }; const server = new ApolloServer({ typeDefs, resolvers }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Sample Program
This program sets up a GraphQL server that responds to a 'message' query with a simple string.
GraphQL
const { ApolloServer, gql } = require('apollo-server'); // Define schema with one query const typeDefs = gql` type Query { message: String } `; // Define resolver to return data const resolvers = { Query: { message: () => 'GraphQL server is running!' } }; // Create server with schema and resolvers const server = new ApolloServer({ typeDefs, resolvers }); // Start server and log URL server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
OutputSuccess
Important Notes
Setting up the server is the first step to use GraphQL in any app.
Server listens for client requests and sends back only requested data.
Common mistake: forgetting to define resolvers, so queries return errors.
Summary
Server setup lets GraphQL receive and answer data requests.
It connects schema (data shape) with resolvers (how to get data).
Without a server, GraphQL queries cannot run or return data.