Convert Figma logo to code with AI

graphql logoexpress-graphql

Create a GraphQL HTTP server with Express.

6,340
538
6,340
55

Top Related Projects

🌍  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.

A reference implementation of GraphQL for JavaScript

Awesome list of GraphQL

9,900

An implementation of GraphQL for Go / Golang

GraphQL framework for Python

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

Quick Overview

The express-graphql project is a Node.js library that provides a way to build a GraphQL server using the Express web application framework. It allows developers to create a GraphQL API and handle incoming GraphQL queries, mutations, and subscriptions.

Pros

  • Ease of Use: The library provides a simple and straightforward way to set up a GraphQL server with Express, making it easy for developers to get started with GraphQL.
  • Flexibility: express-graphql supports various GraphQL features, including queries, mutations, subscriptions, and schema introspection, allowing developers to build robust GraphQL APIs.
  • Middleware Integration: The library integrates well with the Express middleware ecosystem, allowing developers to leverage other Express-compatible middleware and tools.
  • Active Development: The project is actively maintained and has a large community, ensuring ongoing support and improvements.

Cons

  • Limited Functionality: While express-graphql provides a solid foundation for building GraphQL servers, it may lack some advanced features or customization options compared to other GraphQL server implementations.
  • Performance Overhead: The additional layer of abstraction between Express and GraphQL may introduce some performance overhead, especially for high-traffic applications.
  • Dependency on Express: The library is tightly coupled with the Express web framework, which may be a limitation for developers who prefer to use other web frameworks or want a more framework-agnostic GraphQL server solution.
  • Steep Learning Curve: Developers new to GraphQL may find the initial setup and configuration of express-graphql to be more complex than some other GraphQL server options.

Code Examples

Here are a few code examples demonstrating the usage of express-graphql:

  1. Setting up a basic GraphQL server:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

// Define the GraphQL schema
const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// Resolver function for the "hello" query
const root = {
  hello: () => 'Hello, world!',
};

const app = express();
app.use(
  '/graphql',
  graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
  })
);

app.listen(4000, () => console.log('GraphQL server running on port 4000'));
  1. Handling mutations:
const schema = buildSchema(`
  type Mutation {
    addUser(name: String): User
  }

  type User {
    id: ID!
    name: String
  }
`);

const root = {
  addUser: ({ name }) => {
    const user = { id: users.length + 1, name };
    users.push(user);
    return user;
  },
};
  1. Implementing GraphQL subscriptions:
const { subscribe, publish } = require('graphql-subscriptions');

const schema = buildSchema(`
  type Subscription {
    messageAdded: String
  }

  type Mutation {
    addMessage(message: String): String
  }
`);

const root = {
  addMessage: (args) => {
    const message = args.message;
    publish('messageAdded', message);
    return message;
  },
  subscribe: () => subscribe('messageAdded'),
};

Getting Started

To get started with express-graphql, follow these steps:

  1. Install the required dependencies:
npm install express express-graphql graphql
  1. Create a new file, e.g., server.js, and set up the basic GraphQL server:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

// Define the GraphQL schema
const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// Resolver function for the "hello" query
const root = {
  hello: () => 'Hello, world!',
};

const app = express();
app.use(
  '/

Competitor Comparisons

🌍  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.

Pros of Apollo Server

  • Integrated Tooling: Apollo Server comes with built-in support for features like GraphQL Playground, a powerful GraphQL IDE, and GraphQL Subscriptions, making it easier to develop and test GraphQL APIs.
  • Scalability: Apollo Server is designed to be highly scalable, with features like caching, batching, and federation that help handle large amounts of data and traffic.
  • Ecosystem Integration: Apollo Server integrates well with other popular technologies in the JavaScript ecosystem, such as Express, Koa, and Fastify, making it easier to integrate into existing projects.

Cons of Apollo Server

  • Complexity: Apollo Server can be more complex to set up and configure compared to express-graphql, especially for simpler use cases.
  • Performance Overhead: The additional features and tooling provided by Apollo Server may come with a slight performance overhead compared to a more lightweight solution like express-graphql.

Code Comparison

Express-GraphQL:

const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./schema');

const app = express();

app.use('/graphql', graphqlHTTP({
  schema,
  graphiql: true,
}));

app.listen(3000, () => {
  console.log('GraphQL server running on port 3000');
});

Apollo Server:

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

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

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

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

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 3000 }, () =>
  console.log(`🚀 Server ready at http://localhost:3000${server.graphqlPath}`)
);

A reference implementation of GraphQL for JavaScript

Pros of graphql-js

  • graphql-js is a standalone library, allowing for more flexibility in integrating it into different environments and frameworks.
  • graphql-js has a more extensive set of features and utilities, such as introspection, schema validation, and execution.
  • graphql-js is more actively maintained and has a larger community, with more contributors and a wider range of resources available.

Cons of graphql-js

  • graphql-js requires more manual setup and configuration compared to express-graphql, which provides a more opinionated and easier-to-use solution.
  • graphql-js may have a steeper learning curve for developers who are new to GraphQL, as it requires a deeper understanding of the core concepts.

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

express-graphql:

const express = require('express');
const graphqlHTTP = require('express-graphql');

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

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

const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));

Awesome list of GraphQL

Pros of Awesome GraphQL

  • Comprehensive list of GraphQL resources, including libraries, tools, and tutorials, making it a valuable resource for developers.
  • Regularly updated with new additions, ensuring the information remains current.
  • Organized into different categories, making it easy to find relevant resources.

Cons of Awesome GraphQL

  • Not a standalone project like express-graphql, so it doesn't provide any direct functionality.
  • The repository is primarily a curated list, so it doesn't offer any code examples or implementation details.
  • The maintenance of the repository relies on community contributions, which can lead to inconsistencies or outdated information.

Code Comparison

// express-graphql
const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./schema');

const app = express();
app.use('/graphql', graphqlHTTP({
  schema,
  graphiql: true,
}));

app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
// Awesome GraphQL
# GraphQL
- [GraphQL](https://graphql.org/) - A query language for APIs and a runtime for fulfilling those queries with your existing data.
- [GraphQL Specification](https://github.com/graphql/graphql-spec) - The GraphQL Specification.
- [GraphQL Ecosystem](https://graphql.org/ecosystem/) - A list of GraphQL libraries, tools, and more.
9,900

An implementation of GraphQL for Go / Golang

Pros of graphql-go/graphql

  • Performance: graphql-go/graphql is written in Go, which is known for its performance and efficiency, making it a suitable choice for high-traffic applications.
  • Simplicity: The library provides a straightforward and easy-to-use API, making it accessible for developers who are new to GraphQL.
  • Flexibility: graphql-go/graphql offers a flexible and extensible design, allowing developers to customize and extend the library to fit their specific needs.

Cons of graphql-go/graphql

  • Ecosystem: The GraphQL ecosystem in Go is not as mature as the one in JavaScript, which may limit the availability of third-party tools and libraries.
  • Learning Curve: Developers who are more familiar with JavaScript and the Express ecosystem may find the transition to Go and the graphql-go/graphql library more challenging.
  • Tooling: The tooling and development experience around graphql-go/graphql may not be as polished as the one for graphql/express-graphql, which has a larger community and more established tooling.

Code Comparison

Here's a brief code comparison between graphql/express-graphql and graphql-go/graphql:

graphql/express-graphql:

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

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

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

const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

app.listen(4000, () => console.log('Running a GraphQL API server at http://localhost:4000/graphql'));

graphql-go/graphql:

package main

import (
    "fmt"
    "net/http"

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

func main() {
    fields := graphql.Fields{
        "hello": &graphql.Field{
            Type: graphql.String,
            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                return "Hello, world!", nil
            },
        },
    }

    rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
    schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
    schema, _ := graphql.NewSchema(schemaConfig)

    http.Handle("/graphql", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        result := graphql.Do(graphql.Params{
            Schema:        schema,
            RequestString: r.URL.Query().Get("query"),
        })
        fmt.Fprintf(w, "%+v", result)
    }))

    fmt.Println("Server is running on port 4000")
    http.ListenAndServe(":4000", nil)
}

GraphQL framework for Python

Pros of Graphene

  • Graphene provides a more Pythonic and intuitive API for building GraphQL schemas, compared to the more verbose and lower-level approach of express-graphql.
  • Graphene integrates well with various Python ORMs and data sources, making it easier to build GraphQL APIs on top of existing data models.
  • Graphene has a rich ecosystem of plugins and extensions, providing additional functionality and flexibility.

Cons of Graphene

  • Graphene may have a steeper learning curve for developers who are more familiar with the express-graphql approach.
  • The Graphene ecosystem is primarily focused on the Python community, while express-graphql has a larger and more diverse community.

Code Comparison

express-graphql (JavaScript)

const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./schema');

const app = express();

app.use('/graphql', graphqlHTTP({
  schema,
  graphiql: true
}));

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Graphene (Python)

import graphene

class Query(graphene.ObjectType):
    hello = graphene.String()

    def resolve_hello(self, info):
        return "World"

schema = graphene.Schema(query=Query)

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

Pros of Hasura GraphQL Engine

  • Hasura provides a fully managed GraphQL backend, reducing the need for manual GraphQL server setup and configuration.
  • Hasura automatically generates a GraphQL API from a PostgreSQL database, making it easier to expose data to clients.
  • Hasura offers built-in features like access control, event triggers, and remote schemas, which can simplify the development process.

Cons of Hasura GraphQL Engine

  • Hasura's opinionated approach may not fit all use cases, and it may be less flexible than a custom-built GraphQL server.
  • Hasura's pricing model, which is based on the number of active users, may not be suitable for all projects.
  • Hasura's reliance on PostgreSQL as the underlying database may be a limitation for projects that require support for other database systems.

Code Comparison

Here's a brief code comparison between express-graphql and graphql-engine:

express-graphql:

const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./schema');

const app = express();

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));

app.listen(4000, () => {
  console.log('GraphQL server running on http://localhost:4000/graphql');
});

graphql-engine:

version: 2
endpoint: http://localhost:8080/v1/graphql
metadata_directory: metadata

The express-graphql code sets up a GraphQL server using the express-graphql middleware, while the graphql-engine code is a configuration file that defines the GraphQL server's endpoint and metadata directory.

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

If you still need to use express-graphql, please read the previous version of this readme.

This library is deprecated

express-graphql was the first official reference implementation of using GraphQL with HTTP. It has existed since 2015 and was mostly unmaintained in recent years.

The official GraphQL over HTTP work group is standardizing the way you transport GraphQL over HTTP and it made great progress bringing up the need for a fresh reference implementation.

Please read the GraphQL over HTTP spec for detailed implementation information.

Say hello to graphql-http

graphql-http is now the GraphQL official reference implementation of the GraphQL over HTTP spec.

For users

As a reference implementation, graphql-http implements exclusively the GraphQL over HTTP spec.

In case you're seeking for a full-featured experience (with file uploads, @defer/@stream directives, subscriptions, etc.), you're recommended to use some of the great JavaScript GraphQL server options:

For library authors

Being the official GraphQL over HTTP spec reference implementation, graphql-http follows the specification strictly without any additional features (like file uploads, @stream/@defer directives and subscriptions).

Having said this, graphql-http is mostly aimed for library authors and simple server setups, where the requirements are exact to what the aforementioned spec offers.

Spec compliance audit suite

Suite of tests used to audit an HTTP server for GraphQL over HTTP spec compliance is available in graphql-http and you can use it to check your own, or other, servers!

Additionally, graphql-http will maintain a list of GraphQL servers in the ecosystem and share their compliance results (see them here).

NPM DownloadsLast 30 Days