Convert Figma logo to code with AI

apollographql logoapollo-server

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.

13,768
2,032
13,768
102

Top Related Projects

A reference implementation of GraphQL for JavaScript

🧘 Rewrite of a fully-featured GraphQL Server with focus on easy setup, performance & great developer experience. The core of Yoga implements WHATWG Fetch API and can run/deploy on any JS environment.

9,900

An implementation of GraphQL for Go / Golang

Awesome list of GraphQL

GraphQL Java implementation

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.

Quick Overview

Apollo Server is a GraphQL server implementation for Node.js. It's designed to be production-ready and easily integrates with various Node.js HTTP frameworks. Apollo Server provides a flexible, extensible platform for building GraphQL APIs that can be used with any data source.

Pros

  • Easy to set up and use, with minimal boilerplate code required
  • Excellent integration with the Apollo Client ecosystem
  • Robust features like automatic persisted queries, caching, and error handling
  • Extensive documentation and active community support

Cons

  • Learning curve for developers new to GraphQL
  • Can be overkill for small projects or simple APIs
  • Performance overhead compared to REST APIs for certain use cases
  • Requires careful schema design to avoid performance issues with complex queries

Code Examples

  1. Basic Apollo Server setup:
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

const typeDefs = `#graphql
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

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

const { url } = await startStandaloneServer(server);
console.log(`🚀 Server ready at ${url}`);
  1. Using Apollo Server with Express:
import express from 'express';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';

const app = express();
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();

app.use('/graphql', expressMiddleware(server));
app.listen(4000, () => console.log('Server running on port 4000'));
  1. Implementing a mutation:
const typeDefs = `#graphql
  type Mutation {
    addBook(title: String!, author: String!): Book
  }

  type Book {
    title: String
    author: String
  }
`;

const resolvers = {
  Mutation: {
    addBook: (_, { title, author }) => {
      const newBook = { title, author };
      books.push(newBook);
      return newBook;
    },
  },
};

Getting Started

  1. Install Apollo Server:

    npm install @apollo/server graphql
    
  2. Create a new file (e.g., server.js) and add the following code:

    import { ApolloServer } from '@apollo/server';
    import { startStandaloneServer } from '@apollo/server/standalone';
    
    const typeDefs = `#graphql
      type Query {
        hello: String
      }
    `;
    
    const resolvers = {
      Query: {
        hello: () => 'Hello world!',
      },
    };
    
    const server = new ApolloServer({
      typeDefs,
      resolvers,
    });
    
    const { url } = await startStandaloneServer(server);
    console.log(`🚀 Server ready at ${url}`);
    
  3. Run the server:

    node server.js
    
  4. Open a browser and navigate to the URL printed in the console to access the GraphQL playground.

Competitor Comparisons

A reference implementation of GraphQL for JavaScript

Pros of graphql-js

  • Reference implementation of GraphQL, ensuring strict adherence to the specification
  • Lightweight and flexible, allowing for custom integrations and extensions
  • Provides low-level GraphQL operations, ideal for building custom GraphQL servers

Cons of graphql-js

  • Requires more setup and configuration compared to Apollo Server
  • Less out-of-the-box features and tooling for production-ready GraphQL servers
  • Steeper learning curve for developers new to GraphQL

Code Comparison

graphql-js:

const { graphql, buildSchema } = require('graphql');

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

const root = { hello: () => 'Hello world!' };

graphql(schema, '{ hello }', root).then((response) => {
  console.log(response);
});

Apollo Server:

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}`);
});

🧘 Rewrite of a fully-featured GraphQL Server with focus on easy setup, performance & great developer experience. The core of Yoga implements WHATWG Fetch API and can run/deploy on any JS environment.

Pros of GraphQL Yoga

  • Lightweight and flexible, with a modular architecture
  • Easy setup and configuration, with sensible defaults
  • Better TypeScript support and type safety

Cons of GraphQL Yoga

  • Smaller ecosystem and community compared to Apollo Server
  • Less extensive documentation and fewer learning resources
  • May lack some advanced features found in Apollo Server

Code Comparison

Apollo Server:

const server = new ApolloServer({
  typeDefs,
  resolvers,
});
await server.start();
const { url } = await startStandaloneServer(server);
console.log(`🚀 Server ready at ${url}`);

GraphQL Yoga:

const server = createServer({
  schema,
});
server.start();

GraphQL Yoga offers a more concise setup, while Apollo Server provides a more structured approach with explicit server start and standalone server creation.

Both Apollo Server and GraphQL Yoga are popular choices for building GraphQL servers in JavaScript/TypeScript environments. Apollo Server has a larger ecosystem and more extensive features, making it suitable for complex, enterprise-level applications. GraphQL Yoga, on the other hand, focuses on simplicity and flexibility, making it an excellent choice for smaller projects or developers who prefer a more lightweight solution.

The choice between the two depends on project requirements, team expertise, and specific use cases. Apollo Server may be preferable for larger teams and projects requiring extensive features, while GraphQL Yoga could be ideal for developers seeking a simpler, more flexible GraphQL server solution.

9,900

An implementation of GraphQL for Go / Golang

Pros of graphql

  • Native Go implementation, offering better performance for Go-based applications
  • Lightweight and minimalistic, allowing for more flexibility in implementation
  • Closer to the GraphQL specification, providing a more "pure" GraphQL experience

Cons of graphql

  • Less feature-rich compared to Apollo Server, requiring more manual setup
  • Smaller community and ecosystem, resulting in fewer resources and third-party tools
  • Limited built-in tooling for things like subscriptions and file uploads

Code Comparison

apollo-server (JavaScript):

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 });

graphql (Go):

package main

import (
    "github.com/graphql-go/graphql"
)

var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
    Query: graphql.NewObject(graphql.ObjectConfig{
        Name: "RootQuery",
        Fields: graphql.Fields{
            "hello": &graphql.Field{
                Type: graphql.String,
                Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                    return "Hello world!", nil
                },
            },
        },
    }),
})

Awesome list of GraphQL

Pros of awesome-graphql

  • Comprehensive collection of GraphQL resources, tools, and libraries
  • Community-driven with contributions from various developers
  • Covers a wide range of GraphQL-related topics and ecosystems

Cons of awesome-graphql

  • Not an actual GraphQL implementation or server
  • Requires manual curation and may not always be up-to-date
  • Lacks specific features or functionalities found in Apollo Server

Code comparison

While a direct code comparison isn't relevant due to the nature of these repositories, here's a brief example of how they differ:

awesome-graphql (README.md):

## GraphQL Implementations
- [graphql-js](https://github.com/graphql/graphql-js) - A reference implementation of GraphQL for JavaScript
- [graphql-go](https://github.com/graphql-go/graphql) - GraphQL for Go / Golang

Apollo Server (index.js):

const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

awesome-graphql serves as a curated list of GraphQL resources, while Apollo Server is an actual GraphQL server implementation. awesome-graphql is beneficial for discovering various GraphQL tools and libraries, but it doesn't provide the out-of-the-box functionality that Apollo Server offers for building GraphQL APIs.

GraphQL Java implementation

Pros of graphql-java

  • More flexible and customizable for Java-based projects
  • Better integration with existing Java ecosystems and frameworks
  • Supports a wider range of Java versions

Cons of graphql-java

  • Steeper learning curve for developers new to GraphQL
  • Less opinionated, requiring more manual configuration
  • Smaller community and ecosystem compared to Apollo Server

Code Comparison

graphql-java:

GraphQLSchema schema = GraphQLSchema.newSchema()
    .query(queryType)
    .build();
GraphQL graphQL = GraphQL.newGraphQL(schema).build();
ExecutionResult result = graphQL.execute(query);

Apollo Server:

const server = new ApolloServer({
  typeDefs,
  resolvers,
});
await server.start();
server.applyMiddleware({ app });

Summary

graphql-java is a robust Java implementation of GraphQL, offering more flexibility and customization options for Java-based projects. It integrates well with existing Java ecosystems and supports a wider range of Java versions. However, it has a steeper learning curve and requires more manual configuration compared to Apollo Server.

Apollo Server, on the other hand, provides a more opinionated and easier-to-use solution for JavaScript/Node.js environments. It has a larger community and ecosystem, making it easier to find resources and support. The code comparison shows that Apollo Server requires less boilerplate code to set up a GraphQL server compared to graphql-java.

Choose graphql-java for Java-based projects that require fine-grained control and customization, while Apollo Server is better suited for rapid development in JavaScript environments with its simpler setup and extensive ecosystem.

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.

Pros of GraphQL Engine

  • Automatic GraphQL API generation from existing databases
  • Real-time subscriptions and live queries out of the box
  • Built-in authorization and access control system

Cons of GraphQL Engine

  • Less flexibility for custom resolvers and business logic
  • Steeper learning curve for non-database-centric applications
  • Limited support for non-PostgreSQL databases

Code Comparison

Apollo Server example:

const resolvers = {
  Query: {
    books: () => books,
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

GraphQL Engine example:

tables:
  - table:
      schema: public
      name: books
    select_permissions:
      - role: user
        permission:
          columns: [id, title, author]
          filter: {}

GraphQL Engine automatically generates the API based on the database schema and permissions, while Apollo Server requires manual resolver implementation. GraphQL Engine's approach is more declarative and database-centric, whereas Apollo Server offers more flexibility for custom logic and data sources.

Both projects have their strengths, with GraphQL Engine excelling in rapid development for database-driven applications and Apollo Server providing more customization options for complex use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

@apollo/server

This @apollo/server package is new with Apollo Server 4. Previous major versions of Apollo Server used a set of package names starting with apollo-server, such as apollo-server, apollo-server-express, apollo-server-core, etc.

npm version Build Status Join the community Join our Discord server


Announcement:
Join 1000+ engineers at GraphQL Summit for talks, workshops, and office hours, Oct 8-10 in NYC. Get your pass here ->


A TypeScript/JavaScript GraphQL server

Apollo Server is an open-source, spec-compliant GraphQL server that's compatible with any GraphQL client, including Apollo Client. It's the best way to build a production-ready, self-documenting GraphQL API that can use data from any source.

You can use Apollo Server as:

Apollo Server provides a simple API for integrating with any Node.js web framework or serverless environment. The @apollo/server package itself ships with a minimally-configurable, standalone web server which handles CORS and body parsing out of the box. Integrations with other environments are community-maintained.

Apollo Server provides:

  • Straightforward setup, so your client developers can start fetching data quickly
  • Incremental adoption, enabling you to add features as they're needed
  • Universal compatibility with any data source, any build tool, and any GraphQL client
  • Production readiness, enabling you to confidently run your graph in production

Documentation

Full documentation for Apollo Server is available on our documentation site. This README shows the basics of getting a server running (both standalone and with Express), but most features are only documented on our docs site.

Getting started: standalone server

You can also check out the getting started guide in the Apollo Server docs for more details, including examples in both TypeScript and JavaScript.

Apollo Server's standalone server lets you get a GraphQL server up and running quickly without needing to set up an HTTP server yourself. It allows all the same configuration of GraphQL logic as the Express integration, but does not provide the ability to make fine-grained tweaks to the HTTP-specific behavior of your server.

First, install Apollo Server and the JavaScript implementation of the core GraphQL algorithms:

npm install @apollo/server graphql

Then, write the following to server.mjs. (By using the .mjs extension, Node lets you use the await keyword at the top level.)

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

// The GraphQL schema
const typeDefs = `#graphql
  type Query {
    hello: String
  }
`;

// A map of functions which return data for the schema.
const resolvers = {
  Query: {
    hello: () => 'world',
  },
};

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

const { url } = await startStandaloneServer(server);
console.log(`🚀 Server ready at ${url}`);

Now run your server with:

node server.mjs

Open the URL it prints in a web browser. It will show Apollo Sandbox, a web-based tool for running GraphQL operations. Try running the operation query { hello }!

Getting started: Express middleware

Apollo Server's built-in Express middleware lets you run your GraphQL server as part of an app built with Express, the most popular web framework for Node.

First, install Apollo Server, the JavaScript implementation of the core GraphQL algorithms, Express, and two common Express middleware packages:

npm install @apollo/server graphql express cors body-parser

If using Typescript you may also need to install additional type declaration packages as development dependencies to avoid common errors when importing the above packages (i.e. Could not find a declaration file for module 'cors'):

npm install --save-dev @types/cors @types/express @types/body-parser

Then, write the following to server.mjs. (By using the .mjs extension, Node lets you use the await keyword at the top level.)

import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer'
import express from 'express';
import http from 'http';
import cors from 'cors';
import bodyParser from 'body-parser';

// The GraphQL schema
const typeDefs = `#graphql
  type Query {
    hello: String
  }
`;

// A map of functions which return data for the schema.
const resolvers = {
  Query: {
    hello: () => 'world',
  },
};

const app = express();
const httpServer = http.createServer(app);

// Set up Apollo Server
const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();

app.use(
  cors(),
  bodyParser.json(),
  expressMiddleware(server),
);

await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000`);

Now run your server with:

node server.mjs

Open the URL it prints in a web browser. It will show Apollo Sandbox, a web-based tool for running GraphQL operations. Try running the operation query { hello }!

NPM DownloadsLast 30 Days