Many different programming languages support GraphQL. This list contains some of the more popular server-side frameworks, client libraries, services, and other useful stuff.
In addition to the GraphQL reference implementations in JavaScript, server libraries include:
using System;using GraphQL;using GraphQL.Types;public class Program{public static void Main(string[] args){var schema = Schema.For(@"type Query {hello: String}");var json = schema.Execute(_ =>{_.Query = "{ hello }";_.Root = new { Hello = "Hello World!" };});Console.WriteLine(json);}}
A set of reusable GraphQL components for Clojure conforming to the data structures given in alumbra.spec.
(require '[alumbra.core :as alumbra]'[claro.data :as data])(def schema"type Person { name: String!, friends: [Person!]! }type QueryRoot { person(id: ID!): Person, me: Person! }schema { query: QueryRoot }")(defrecord Person [id]data/Resolvable(resolve! [_ _]{:name (str "Person #" id):friends (map ->Person (range (inc id) (+ id 3)))}))(def QueryRoot{:person (map->Person {}):me (map->Person {:id 0})})(def app(alumbra/handler{:schema schema:query QueryRoot}))(defonce my-graphql-server(aleph.http/start-server #'app {:port 3000}))
$ curl -XPOST "http://0:3000" -H'Content-Type: application/json' -d'{"query": "{ me { name, friends { name } } }"}'{"data":{"me":{"name":"Person #0","friends":[{"name":"Person #1"},{"name":"Person #2"}]}}}
A Clojure library that provides a GraphQL implementation.
Code that executes a hello world GraphQL query with graphql-clj:
(def schema "type QueryRoot {hello: String}")(defn resolver-fn [type-name field-name](get-in {"QueryRoot" {"hello" (fn [context parent & rest]"Hello world!")}}[type-name field-name]))(require '[graphql-clj.executor :as executor])(executor/execute nil schema resolver-fn "{ hello }")
A full implementation of the GraphQL specification that aims to maintain external compliance with the specification.
Core Library - The GORM GraphQL library provides functionality to generate a GraphQL schema based on your GORM entities. In addition to mapping domain classes to a GraphQL schema, the core library also provides default implementations of "data fetchers" to query, update, and delete data through executions of the schema.
Grails Plugin - In a addition to the Core Library, the GORM GraphQL Grails Plugin:
See the documentation for more information.
GQL is a Groovy library for GraphQL
A Java library for building GraphQL APIs.
Code that executes a hello world GraphQL query with graphql-java:
import graphql.ExecutionResult;import graphql.GraphQL;import graphql.schema.GraphQLSchema;import graphql.schema.StaticDataFetcher;import graphql.schema.idl.RuntimeWiring;import graphql.schema.idl.SchemaGenerator;import graphql.schema.idl.SchemaParser;import graphql.schema.idl.TypeDefinitionRegistry;import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;public class HelloWorld {public static void main(String[] args) {String schema = "type Query{hello: String} schema{query: Query}";SchemaParser schemaParser = new SchemaParser();TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);RuntimeWiring runtimeWiring = new RuntimeWiring().type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world"))).build();SchemaGenerator schemaGenerator = new SchemaGenerator();GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();ExecutionResult executionResult = build.execute("{hello}");System.out.println(executionResult.getData().toString());// Prints: {hello=world}}}
See the graphql-java docs for more information on setup.
The reference implementation of the GraphQL specification, designed for running GraphQL in a Node.js environment.
To run a GraphQL.js hello world script from the command line:
npm install graphql
Then run node hello.js with this code in hello.js:
var { graphql, buildSchema } = require('graphql');var schema = buildSchema(`type Query {hello: String}`);var root = { hello: () => 'Hello world!' };graphql(schema, '{ hello }', root).then((response) => {console.log(response);});
The reference implementation of a GraphQL API server over an Express webserver. You can use this to run GraphQL in conjunction with a regular Express webserver, or as a standalone GraphQL server.
To run an express-graphql hello world server:
npm install express express-graphql graphql
Then run node server.js with this code in server.js:
var express = require('express');var { graphqlHTTP } = require('express-graphql');var { buildSchema } = require('graphql');var schema = buildSchema(`type Query {hello: String}`);var root = { hello: () => 'Hello world!' };var app = express();app.use('/graphql', graphqlHTTP({schema: schema,rootValue: root,graphiql: true,}));app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));
A set of GraphQL server packages from Apollo that work with various Node.js HTTP frameworks (Express, Connect, Hapi, Koa etc).
To run a hello world server with apollo-server-express:
npm install apollo-server-express express
Then run node server.js with this code in server.js:
const express = require('express');const { ApolloServer, gql } = require('apollo-server-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: 4000 }, () =>console.log('Now browse to http://localhost:4000' + server.graphqlPath));
Apollo Server also supports all Node.js HTTP server frameworks: Express, Connect, HAPI, Koa and NestJs.
API Platform is a fully-featured, flexible and extensible API framework built on top of Symfony. The following class is enough to create both a Relay-compatible GraphQL server and a hypermedia API supporting modern REST formats (JSON-LD, JSONAPI...):
<?phpnamespace App\Entity;use ApiPlatform\Core\Annotation\ApiResource;use Doctrine\ORM\Mapping as ORM;/*** Greet someone!** @ApiResource* @ORM\Entity*/class Greeting{/*** @ORM\Id* @ORM\Column(type="guid")*/public $id;/*** @var string Your nice message** @ORM\Column*/public $hello;}
Other API Platform features include data validation, authentication, authorization, deprecations, cache and GraphiQL integration.
GraphQLite is a library that offers an annotations-based syntax for GraphQL schema definition. It is framework agnostic with bindings available for Symfony and Laravel.
This code declares a "product" query and a "Product" Type:
class ProductController{/*** @Query()*/public function product(string $id): Product{// Some code that looks for a product and returns it.}}/*** @Type()*/class Product{/*** @Field()*/public function getName(): string{return $this->name;}// ...}
Other GraphQLite features include validation, security, error handling, loading via data-loader pattern...
Siler is a PHP library powered with high-level abstractions to work with GraphQL.
To run a Siler hello world script:
type Query {hello: String}
<?phpdeclare(strict_types=1);require_once '/path/to/vendor/autoload.php';use Siler\Diactoros;use Siler\Graphql;use Siler\Http;$typeDefs = file_get_contents(__DIR__.'/schema.graphql');$resolvers = ['Query' => ['hello' => 'world',],];$schema = Graphql\schema($typeDefs, $resolvers);echo "Server running at http://127.0.0.1:8080";Http\server(Graphql\psr7($schema), function (\Throwable $err) {var_dump($err);return Diactoros\json(['error' => true,'message' => $err->getMessage(),]);})()->run();
It also provides functionality for the construction of a WebSocket Subscriptions Server based on how Apollo works.
A Python library for building GraphQL APIs.
To run a Graphene hello world script:
pip install graphene
Then run python hello.py with this code in hello.py:
import grapheneclass Query(graphene.ObjectType):hello = graphene.String(name=graphene.String(default_value="World"))def resolve_hello(self, info, name):return 'Hello ' + nameschema = graphene.Schema(query=Query)result = schema.execute('{ hello }')print(result.data['hello']) # "Hello World"
There are also nice bindings for Relay, Django, SQLAlchemy, and Google App Engine.
A Ruby library for building GraphQL APIs.
To run a hello world script with graphql-ruby:
gem install graphql
Then run ruby hello.rb with this code in hello.rb:
require 'graphql'class QueryType < GraphQL::Schema::Objectgraphql_name 'Query'field :hello dotype types.Stringresolve -> (obj, args, ctx) { 'Hello world!' }endendclass Schema < GraphQL::Schemaquery QueryTypeendputs Schema.execute('{ hello }').to_json
There are also nice bindings for Relay and Rails.
A high performance web server with support for GraphQL. Agoo strives for a simple, easy to use API for GraphQL.
require 'agoo'class Querydef hello'hello'endendclass Schemaattr_reader :querydef initialize@query = Query.new()endendAgoo::Server.init(6464, 'root', thread_count: 1, graphql: '/graphql')Agoo::Server.start()Agoo::GraphQL.schema(Schema.new) {Agoo::GraphQL.load(%^type Query { hello: String }^)}sleep# To run this GraphQL example type the following then go to a browser and enter# a URL of localhost:6464/graphql?query={hello}## ruby hello.rb
An example of a hello world GraphQL schema and query with sangria:
import sangria.schema._import sangria.execution._import sangria.macros._val QueryType = ObjectType("Query", fields[Unit, Unit](Field("hello", StringType, resolve = _ ⇒ "Hello world!")))val schema = Schema(QueryType)val query = graphql"{ hello }"Executor.execute(schema, query) map println
Apollo Android: A strongly-typed, caching GraphQL client for the JVM, Android and Kotlin native.
Nodes: A GraphQL JVM Client designed for constructing queries from standard model definitions. By American Express.
fetch.