GraphQL

Code

using GraphQL

Because GraphQL is a communication pattern, there are many tools to help you get started working which support GraphQL in all sorts of languages.

Language Support

C / C++

Tools

A GraphQL query language parser in C++ with C and C++ APIs.

C# / .NET

Server

.NET Core GraphQL library. Compiles to IQueryable to easily expose a schema from an existing data model (E.g. from an Entity Framework data model)

using System;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Types;
using GraphQL.SystemTextJson; // First add PackageReference to GraphQL.SystemTextJson
public class Program
{
public static async Task Main(string[] args)
{
var schema = Schema.For(@"
type Query {
hello: String
}
");
var json = await schema.ExecuteAsync(_ =>
{
_.Query = "{ hello }";
_.Root = new { Hello = "Hello World!" };
});
Console.WriteLine(json);
}
}

Convert GraphQL to IQueryable

Hot Chocolate

Hot Chocolate is an open-source GraphQL Server for .NET

Hot Chocolate takes the complexity away from building a fully-fledged GraphQL server and lets you focus on delivering the next big thing.

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
WebHost
.CreateDefaultBuilder(args)
.ConfigureServices(services =>
services
.AddGraphQLServer()
.AddQueryType<Query>())
.Configure(builder =>
builder
.UseRouting()
.UseEndpoints(e => e.MapGraphQL()))
.Build()
.Run();
public class Query
{
public Hero GetHero() => new Hero();
}
public class Hero
{
public string Name => "Luke Skywalker";
}

A set of packages for implementing high-performant GraphQL servers in .NET. Faithful implementation of official 2018 Specification. Features batched execution support (aka Data Loader); support for custom scalars; HTTP server based on ASP.NET Core; parsed query cache; modular API construction (equivalent of schema stiching); full introspection support; runtime metrics and quotas.

Client

A GraphQL Client for .NET.

Basic example GraphQL client for .NET.

GraphQL client which supports generating queries from C# classes

Strawberry Shake

Strawberry Shake is a open-source reactive GraphQL client for .NET

Strawberry Shake removes the complexity of state management and lets you interact with local and remote data through GraphQL.

You can use Strawberry Shake to:

  • Generate a C# client from your GraphQL queries.
  • Interact with local and remote data through GraphQL.
  • Use reactive APIs to interact with your state.
client.GetHero
.Watch(ExecutionStrategy.CacheFirst)
.Subscribe(result =>
{
Console.WriteLine(result.Data.Name);
})

Clojure

Server

alumbra

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"}]}}}

graphql-clj

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.

Client

A GraphQL client implemented in Clojurescript with support for websockets.

D

Server

A GraphQL implementaiton for the D Programming Language.

Elixir

Server

GraphQL implementation for Elixir.

An Elixir implementation of Facebook's GraphQL.

Client

Elixir GraphQL Client with HTTP and WebSocket support

A GraphQL client for Elixir

Elm

Client

Library and command-line code generator to create type-safe Elm code for a GraphQL endpoint.

Erlang

Server

GraphQL implementation in Erlang.

Flutter

Client

Ferry is a simple, powerful GraphQL Client for Flutter and Dart.

A GraphQL client implementation in Flutter.

Server

Go generate based graphql server library.

Develop spec compliant GraphQL servers in Go.

An active implementation of GraphQL in Golang (was https://github.com/neelance/graphql-go).

An implementation of GraphQL for Go / Golang.

A Go/Golang library to help construct a graphql-go server supporting react-relay.

A GraphQL implementation with easy schema building, live queries, and batching.

Client

A GraphQL Go client with Mutation, Query and Subscription support.

A GraphQL client implementation in Go.

An elegant low-level HTTP client for GraphQL.

Tools

An instant GraphQL to SQL compiler. Use as a standalone service or a Go library. Formerly super-graph.

Groovy

Server

gorm-graphql

An automatic GraphQL schema generator for GORM

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:

  • Provides a controller to receive and respond to GraphQL requests through HTTP, based on their guidelines.

  • Generates the schema at startup with spring bean configuration to make it easy to extend.

  • Includes a GraphiQL browser enabled by default in development. The browser is accessible at /graphql/browser.

  • Overrides the default data binder to use the data binding provided by Grails

  • Provides a trait to make integration testing of your GraphQL endpoints easier

See the documentation for more information.

GQL is a Groove library for GraphQL

Haskell

Server

Morpheus GraphQL

A Haskell library for building GraphQL APIs.

Hello world example with morpheus-graphql:

# schema.gql
"""
A supernatural being considered divine and sacred
"""
type Deity {
name: String!
power: String @deprecated(reason: "no more supported")
}
type Query {
deity(name: String! = "Morpheus"): Deity!
}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module API (api) where
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.Morpheus (interpreter)
import Data.Morpheus.Document (importGQLDocument)
import Data.Morpheus.Types (RootResolver (..), Undefined (..))
import Data.Text (Text)
importGQLDocument "schema.gql"
rootResolver :: RootResolver IO () Query Undefined Undefined
rootResolver =
RootResolver
{ queryResolver = Query {deity},
mutationResolver = Undefined,
subscriptionResolver = Undefined
}
where
deity DeityArgs {name} =
pure
Deity
{ name = pure name,
power = pure (Just "Shapeshifting")
}
api :: ByteString -> IO ByteString
api = interpreter rootResolver

See morpheus-graphql-examples for more sophisticated APIs.

Mu-Haskell with Mu-GraphQL

A Haskell library for building microservices (gRPC, HTTP) and GraphQL APIs.

Example implementation of a GraphQL server with type-level representation of the schema auto-generated:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
-- imports omitted for brevity...
graphql "Library" "library.graphql" -- all the magic happens here! 🪄🎩
-- ... a bit more code...
libraryServer :: SqlBackend -> ServerT ObjectMapping i Library ServerErrorIO _
libraryServer conn =
resolver
( object @"Book"
( field @"id" bookId,
field @"title" bookTitle,
field @"author" bookAuthor,
field @"imageUrl" bookImage
),
object @"Author"
( field @"id" authorId,
field @"name" authorName,
field @"books" authorBooks
),
object @"Query"
( method @"authors" allAuthors,
method @"books" allBooks
),
object @"Mutation"
( method @"newAuthor" newAuthor,
method @"newBook" newBook
),
object @"Subscription"
(method @"allBooks" allBooksConduit)
)
where
bookId :: Entity Book -> ServerErrorIO Integer
bookId (Entity (BookKey k) _) = pure $ toInteger k
-- ... more resolvers...

See our docs for more information about how to build your own GraphQL server and the library example for a more end-to-end example that includes a client written in Elm!

Client

A strongly-typed GraphQL client implementation in Haksell.

Java / Kotlin

Server

graphql-java

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.

graphql-kotlin

A set of libraries for running GraphQL client and server in Kotlin.

GraphQL Kotlin follows a code first approach for generating your GraphQL schemas. Given the similarities between Kotlin and GraphQL, such as the ability to define nullable/non-nullable types, a schema can be generated from Kotlin code without any separate schema specification. To create a reactive GraphQL web server add following dependency to your Gradle build file:

// build.gradle.kts
implementation("com.expediagroup", "graphql-kotlin-spring-server", latestVersion)

We also need to provide a list of supported packages that can be scanned for exposing your schema objects through reflections. Add following configuration to your application.yml file:

graphql:
packages:
- "com.your.package"

With the above configuration we can now create our schema. In order to expose your queries, mutations and/or subscriptions in the GraphQL schema you simply need to implement corresponding marker interface and they will be automatically picked up by graphql-kotlin-spring-server auto-configuration library.

@Component
class HelloWorldQuery : Query {
fun helloWorld() = "Hello World!!!"
}

This will result in a reactive GraphQL web application with following schema:

type Query {
helloWorld: String!
}

See graphql-kotlin docs for additial details.

KGraphQL

KGraphQL is a Kotlin implementation of GraphQL. It provides a rich DSL to set up the GraphQL schema.

Here's an example on how to create a simple schema based on a kotlin data class plus a property resolver that gets applied onto your class.

data class Article(val id: Int, val text: String)
fun main() {
val schema = KGraphQL.schema {
query("article") {
resolver { id: Int?, text: String ->
Article(id ?: -1, text)
}
}
type<Article> {
property<String>("fullText") {
resolver { article: Article ->
"${article.id}: ${article.text}"
}
}
}
}
schema.execute("""
{
article(id: 5, text: "Hello World") {
id
fullText
}
}
""").let(::println)
}

KGraphQL is using coroutines behind the scenes to provide great asynchronous performance.

See KGraphQL docs for more in depth usage.

Ktor Plugin#

KGraphQL has a Ktor plugin which gives you a fully functional GraphQL server with a single install function call. Example below shows how to set up a GraphQL server within Ktor and it will give you a GraphQL Playground out of the box by entering localhost:8080/graphql.

fun Application.module() {
install(GraphQL) {
playground = true
schema {
query("hello") {
resolver { -> "World!" }
}
}
}
}

You can follow the Ktor tutorial to set up a KGraphQL server with ktor from scratch up.

Client

A strongly-typed, caching GraphQL client for Android, written in Java.

graphql-kotlin

A set of libraries for running GraphQL client and server in Kotlin.

GraphQL Kotlin provides a set of lightweight type-safe GraphQL HTTP clients. The library provides Ktor HTTP client and Spring WebClient based reference implementations as well as allows for custom implementations using other engines. Type-safe data models are generated at build time by the GraphQL Kotlin Gradle and Maven plugins.

To generate Ktor based GraphQL client add following to your Gradle build file:

// build.gradle.kts
import com.expediagroup.graphql.plugin.generator.GraphQLClientType
import com.expediagroup.graphql.plugin.gradle.graphql
plugins {
id("com.expediagroup.graphql") version $latestGraphQLKotlinVersion
}
dependencies {
implementation("com.expediagroup:graphql-kotlin-ktor-client:$latestGraphQLKotlinVersion")
}
graphql {
client {
// target GraphQL endpoint
endpoint = "http://localhost:8080/graphql"
// package for generated client code
packageName = "com.example.generated"
clientType = GraphQLClientType.KTOR
}
}

By default, GraphQL Kotlin plugin will look for query files under src/main/resources. Given helloWorld: String! query we can add following HelloWorldQuery.graphql sample query to our repo:

query HelloWorldQuery {
helloWorld
}

Plugin will generate following client code:

package com.example.generated
import com.expediagroup.graphql.client.GraphQLKtorClient
import com.expediagroup.graphql.types.GraphQLResponse
import kotlin.String
const val HELLO_WORLD_QUERY: String = "query HelloWorldQuery {\n helloWorld\n}"
class HelloWorldQuery(
private val graphQLClient: GraphQLKtorClient<*>
) {
suspend fun execute(requestBuilder: HttpRequestBuilder.() -> Unit = {}): GraphQLResponse<HelloWorldQuery.Result> =
graphQLClient.execute(HELLO_WORLD_QUERY, "HelloWorldQuery", null, requestBuilder)
data class Result(
val helloWorld: String
)
}

We can then execute the client

package com.example.client
import com.expediagroup.graphql.client.GraphQLKtorClient
import com.expediagroup.graphql.generated.HelloWorldQuery
import kotlinx.coroutines.runBlocking
import java.net.URL
fun main() {
val client = GraphQLKtorClient(url = URL("http://localhost:8080/graphql"))
val helloWorldQuery = HelloWorldQuery(client)
runBlocking {
val result = helloWorldQuery.execute()
println("hello world query result: ${result.data?.helloWorld}")
}
client.close()
}

See graphql-kotlin docs for additial details.

A GraphQL JVM Client designed for constructing queries from standard model definitions. By American Express.

Tools

GraphQL Java Generator

GraphQL Java Generator is a tool that generates Java code to speed up development for Client and Server of GraphQL APIs

  • GraphQL Java client: it generates the Java classes that call the GraphQL endpoint, and the POJO that will contain the data returned by the server. The GraphQL endpoint can then be queried by using a simple call to a Java method (see sample below)
  • GraphQL Java server: it is based on graphql-java (listed here above). It generates all the boilerplate code. You'll only have to implement what's specific to your server, which are the joins between the GraphQL types. GraphQL Java Generator is available as a Maven Plugin. A Gradle plugin is coming soon. Please note that GraphQL Java Generator is an accelerator: the generated code doesn’t depend on any library specific to GraphQL Java Generator. So, it helps you to start building application based on graphql-java. Once the code is generated, you can decide to manually edit it as any standard java application, and get rid of GraphQL Java Generator. Of course you can, and should, according to us :), continue using GraphQL Java Generator when your projet evolves.

Julia

Client

A Julia GraphQL server implementation.

OCaml / Reason

Server

GraphQL server library for OCaml and Reason

Perl

Server

graphql-perl

A Perl port of GraphQL reference implementation

PHP

Server

API Platform

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...):

<?php
namespace AppEntity;
use ApiPlatformCoreAnnotationApiResource;
use DoctrineORMMapping as ORM;
/**
* Greet someone!
*
* @ApiResource
* @ORMEntity
*/
class Greeting
{
/**
* @ORMId
* @ORMColumn(type="guid")
*/
public $id;
/**
* @var string Your nice message
*
* @ORMColumn
*/
public $hello;
}

Other API Platform features include data validation, authentication, authorization, deprecations, cache and GraphiQL integration.

GraPHPinator

A GraphQL implementation for modern PHP. Includes features from latest draft, middleware directives and modules with extra functionality.

GraPHPinator is feature complete PHP implementation of GraphQL server. Its job is transformation of query string into resolved Json result for a given Schema.

  • Aims to be compliant with the latest draft of GraphQL specification.
  • Fully typesafe, and therefore minimum required PHP version is 8.0. Sacrafices a tiny bit of convenience for huge amount of clarity and safety - no random configuration arrays, no mixed types, no variable function arguments - this library doesnt try to save you from verbosity, but makes sure you always know what you've got.
  • Code first.
  • Flexible. Easy to extend with extra functionality using Modules or middleware Directives.
  • Includes some opt-in extensions which are out of scope of official specs:
  • Project is composed from multiple smaller packages, which may be used standalone:
    • Tokenizer - Lexical analyzer of GraphQL document.
    • Parser - Syntactic analyzer of GraphQL document.

A GraphQL server for WordPress. Based on GraphQL by PoP

GraphQL by PoP

CMS-agnostic GraphQL server in PHP. It follows the code-first approach, generating the schema dynamically

GraphQL by PoP follows the code-first approach to generate the schema (it can be customized for different clients/applications). Fields are dynamically "subscribed" to types, and may or may not be added to the schema depending on the context.

This is how a User type is satisfied:

class UserTypeResolver extends AbstractTypeResolver
{
public function getTypeName(): string
{
return 'User';
}
public function getSchemaTypeDescription(): ?string
{
$translationAPI = TranslationAPIFacade::getInstance();
return $translationAPI->__('Representation of a user', 'users');
}
public function getID(object $user)
{
return $user->ID;
}
public function getTypeDataLoaderClass(): string
{
return UserTypeDataLoader::class;
}
}

Please notice how the TypeResolver does not indicate which are its fields. It also does not load the objects from the database, but instead delegates this task to a TypeDataLoader.

Adding fields to the type is done via a FieldResolver:

class UserFieldResolver extends AbstractDBDataFieldResolver
{
public static function getClassesToAttachTo(): array
{
return [
UserTypeResolver::class,
];
}
public static function getFieldNamesToResolve(): array
{
return [
'username',
'email',
'url',
];
}
public function getSchemaFieldDescription(
TypeResolverInterface $typeResolver,
string $fieldName
): ?string {
$translationAPI = TranslationAPIFacade::getInstance();
$descriptions = [
'username' => $translationAPI->__("User's username handle", "users"),
'email' => $translationAPI->__("User's email", "users"),
'url' => $translationAPI->__("URL of the user's profile in the website", "users"),
];
return $descriptions[$fieldName];
}
public function getSchemaFieldType(
TypeResolverInterface $typeResolver,
string $fieldName
): ?string {
$types = [
'username' => SchemaDefinition::TYPE_STRING,
'email' => SchemaDefinition::TYPE_EMAIL,
'url' => SchemaDefinition::TYPE_URL,
];
return $types[$fieldName];
}
public function resolveValue(
TypeResolverInterface $typeResolver,
object $user,
string $fieldName,
array $fieldArgs = []
) {
switch ($fieldName) {
case 'username':
return $user->user_login;
case 'email':
return $user->user_email;
case 'url':
$userService = UserServiceFacade::getInstance();
return $userService->getUserProfileURL($user->ID);
}
return null;
}
}

The definition of a field for the GraphQL schema, and its resolution, is split into a multitude of functions from the FieldResolver:

  • getSchemaFieldDescription
  • getSchemaFieldType
  • resolveValue
  • getSchemaFieldArgs
  • isSchemaFieldResponseNonNullable
  • getImplementedInterfaceClasses
  • resolveFieldTypeResolverClass
  • resolveFieldMutationResolverClass

This code is more legible than if all functionality is satisfied through a single function, or through a configuration array, making it easier to implement and maintain the resolvers.

A PHP port of GraphQL reference implementation

A library to help construct a graphql-php server supporting react-relay.

A GraphQL server for Symfony

GraphQLite

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

A GraphQL server for Laravel

A PHP GraphQL Framework.

Use GraphQL to define your Domain Model for CQRS/ES and let serge generate code to handle GraphQL requests.

Siler

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
}
<?php
declare(strict_types=1);
require_once '/path/to/vendor/autoload.php';
use SilerDiactoros;
use SilerGraphql;
use SilerHttp;
$typeDefs = file_get_contents(__DIR__.'/schema.graphql');
$resolvers = [
'Query' => [
'hello' => 'world',
],
];
$schema = Graphqlschema($typeDefs, $resolvers);
echo "Server running at http://127.0.0.1:8080";
Httpserver(Graphqlpsr7($schema), function (Throwable $err) {
var_dump($err);
return Diactorosjson([
'error' => true,
'message' => $err->getMessage(),
]);
})()->run();

It also provides functionality for the construction of a WebSocket Subscriptions Server based on how Apollo works.

A free, open-source WordPress plugin that provides an extendable GraphQL schema and API for any WordPress site

Python

Server

Ariadne

Ariadne is a Python library for implementing GraphQL servers using schema-first approach. It supports both synchronous and asynchronous query execution, ships with batteries included for common GraphQL server problems like query cost validation or performance tracing and has simple API that is easy to extend or replace.

Ariadne can be installed with pip:

pip install ariadne

It ships with many GraphQL server implementations, enabling easy experimentation:

from ariadne import ObjectType, QueryType, gql, make_executable_schema
from ariadne.asgi import GraphQL
# Define types using Schema Definition Language (https://graphql.org/learn/schema/)
# Wrapping string in gql function provides validation and better error traceback
type_defs = gql("""
type Query {
hello: String!
}
""")
# Bind resolver functions to Query's fields using QueryType
query_type = QueryType()
# Resolvers are simple python functions
@query_type.field("hello")
def resolve_hello(*_):
return "Hello world!"
# Create executable GraphQL schema
schema = make_executable_schema(type_defs, query_type)
# Create an ASGI app using the schema, running in debug mode
app = GraphQL(schema, debug=True)

Above server can be ran with uvicorn:

pip install uvicorn
uvicorn example:app

Graphene

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 graphene
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="World"))
def resolve_hello(self, info, name):
return 'Hello ' + name
schema = 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.

Strawberry

Strawberry is a Python library for implementing code first GraphQL servers using modern Python features like type hints.

Here's an example of a Strawberry hello world, first install the library:

pip install strawberry-graphql

Create an app.py file with this content:

import strawberry
@strawberry.type
class Query:
@strawberry.field
def hello(self, name: str = "World") -> str:
return f"Hello {name}"
schema = strawberry.Schema(query=Query)

Then run strawberry server app and you will have a basic schema server running on http://localhost:8000/.

Strawberry also has views for ASGI, Flask and Django and provides utilities like dataloaders and tracing.

Tartiflette

A Python 3.6+ (asyncio) library for building GraphQL APIs.

To run a tartiflette hello world script:

pip install tartiflette

Then run python hello.py with this code in hello.py:

import asyncio
from tartiflette import Engine, Resolver
@Resolver("Query.hello")
async def resolver_hello(parent, args, ctx, info):
return "hello " + args["name"]
async def run():
tftt_engine = Engine("""
type Query {
hello(name: String): String
}
""")
result = await tftt_engine.execute(
query='query { hello(name: "Chuck") }'
)
print(result)
# {'data': {'hello': 'hello Chuck'}}
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(run())

There is also a nice HTTP wrapper.

Client

A GraphQL client in Python.

Simple GraphQL client for Python 2.7+.

A simple Python GraphQL client. Supports generating code generation for types defined in a GraphQL schema.

R

Server

General purpose GraphQL R client

Server

Async-graphql

Async-graphql is a high-performance server-side library that supports all GraphQL specifications.

use async_graphql::*;
struct Query;
#[Object]
impl Query {
/// Returns the sum of a and b
async fn add(&self, a: i32, b: i32) -> i32 {
a + b
}
}

GraphQL server library for Rust

Client

cynic

A bring your own types GraphQL client for Rust

A client library for rust that generates queries from types you provide, verifying that the types match the shape of your schema.

It provides a generator to bootstrap types from existing GraphQL queries.

Usage example:

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
schema_path = "../schemas/starwars.schema.graphql",
query_module = "query_dsl",
graphql_type = "Root",
argument_struct = "FilmArguments"
)]
struct FilmDirectorQuery {
#[arguments(id = &args.id)]
film: Option<Film>,
}
#[derive(cynic::QueryFragment, Debug)]
#[cynic(
schema_path = "../schemas/starwars.schema.graphql",
query_module = "query_dsl",
graphql_type = "Film"
)]
struct Film {
title: Option<String>,
director: Option<String>,
}
#[derive(cynic::FragmentArguments)]
struct FilmArguments {
id: Option<cynic::Id>,
}
fn main() {
use cynic::{QueryBuilder, http::ReqwestBlockingExt};
let query = FilmDirectorQuery::build(&FilmArguments {
id: Some("ZmlsbXM6MQ==".into()),
})
reqwest::blocking::Client::new()
.post("https://swapi-graphql.netlify.com/.netlify/functions/index")
.run_graphql(query)
.unwrap()
}
mod query_dsl {
cynic::query_dsl!("../schemas/starwars.schema.graphql");
}

gql_client

Minimal GraphQL client for Rust

Usage example

use gql_client::Client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let endpoint = "https://graphqlzero.almansi.me/api";
let query = r#"
query AllPostsQuery {
posts {
data {
id
}
}
}
"#;
let client = Client::new(endpoint);
let data: AllPosts = client.query::<AllPosts>(query).await.unwrap();
println!("{:?}" data);
Ok(())
}

Scala

Server

Caliban

Caliban is a purely functional library for building GraphQL servers and clients in Scala

An example of a GraphQL schema and query with caliban:

import caliban.GraphQL.graphQL
import caliban.RootResolver
case class Character(name: String, age: Int)
def getCharacters(): List[Character] = ???
// schema
case class Queries(characters: List[Character])
// resolver
val queries = Queries(getCharacters)
val api = graphQL(RootResolver(queries))
for {
interpreter <- api.interpreter
result <- interpreter.execute("{ characters { name } }")
} yield result

Sangria

A Scala GraphQL library that supports Relay.

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

Client

Functional GraphQL library for Scala, with client code generation and type-safe queries.

Swift / Objective-C

Server

Swift library for building GraphQL schemas/types fast, safely and easily.

Swift library for writing Declarative, Type-Safe GraphQL APIs with Zero Boilerplate.

Client

A GraphQL client for iOS that returns results as query-specific Swift types, and integrates with Xcode to show your Swift source and GraphQL side by side, with inline validation errors.

A Tool for Writing Declarative, Type-Safe and Data-Driven Applications in SwiftUI using GraphQL and Apollo

An Objective-C GraphQL client for iOS.

SwiftGraphQL

A GraphQL client that lets you forget about GraphQL.

SwiftGraphQL is a Swift code generator and a lightweight GraphQL client. It lets you create queries using Swift, and guarantees that every query you create is valid.

The library is centered around three core principles:

🚀 If your project compiles, your queries work. 🦉 Use Swift in favour of GraphQL wherever possible. 🌳 Your application model should be independent of your schema.

Here's a short preview of the SwiftGraphQL code

import SwiftGraphQL
// Define a Swift model.
struct Human: Identifiable {
let id: String
let name: String
let homePlanet: String?
}
// Create a selection.
let human = Selection.Human {
Human(
id: try $0.id(),
name: try $0.name(),
homePlanet: try $0.homePlanet()
)
}
// Construct a query.
let query = Selection.Query {
try $0.humans(human.list)
}
// Perform the query.
send(query, to: "http://swift-graphql.heroku.com") { result in
if let data = try? result.get() {
print(data) // [Human]
}
}

Ruby

Server

graphql-ruby

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::Object
graphql_name 'Query'
field :hello do
type types.String
resolve -> (obj, args, ctx) { 'Hello world!' }
end
end
class Schema < GraphQL::Schema
query QueryType
end
puts Schema.execute('{ hello }').to_json

There are also nice bindings for Relay and Rails.

Agoo

gemagoo

A high performance web server with support for GraphQL. Agoo strives for a simple, easy to use API for GraphQL.

require 'agoo'
class Query
def hello
'hello'
end
end
class Schema
attr_reader :query
def initialize
@query = Query.new()
end
end
Agoo::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

JavaScript

Server

GraphQL.js

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

Apollo Server

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.

Express GraphQL

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

GraphQL Helix

A collection of utility functions for building your own GraphQL HTTP server. You can check out Building a GraphQL server with GraphQL Helix on DEV for a detailed tutorial on getting started.

To run a hello world server with GraphQL Helix:

npm install graphql graphql-helix express

Then run node server.js with this code in server.js:

const express = require('express')
const {
GraphQLObjectType,
GraphQLSchema,
GraphQLString
} = require('graphql');
const {
getGraphQLParameters,
processRequest,
renderGraphiQL,
shouldRenderGraphiQL
} = require('graphql-helix');
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
hello: {
type: GraphQLString,
resolve: () => 'Hello world!',
},
},
}),
});
const app = express();
app.use(express.json());
app.use('/graphql', async (req, res) => {
const request = {
body: req.body,
headers: req.headers,
method: req.method,
query: req.query,
};
if (shouldRenderGraphiQL(request)) {
res.send(renderGraphiQL());
} else {
const { operationName, query, variables } = getGraphQLParameters(request);
const result = await processRequest({
operationName,
query,
variables,
request,
schema,
});
if (result.type === 'RESPONSE') {
result.headers.forEach(({ name, value }) => res.setHeader(name, value));
res.status(result.status);
res.json(result.payload);
} else {
// graphql-helix also supports subscriptions and incremental delivery (i.e. @defer and @stream directives)
// out of the box. See the repo for more complete examples that also implement those features.
}
}
});
app.listen(4000, () =>
console.log('Now browse to http://localhost:4000/graphql');
)

This example uses Express, but GraphQL Helix is framework- and runtime-agnostic -- it can run in Node, Deno and the browser. GraphQL Helix provides you with a handful of utility functions to build your own HTTP server but leaves the ultimate implementation details up to you.

graphql-yoga

Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience

  • Sensible defaults & includes everything you need with minimal setup.
  • Built-in support for GraphQL subscriptions using WebSockets.
  • Works with all GraphQL clients (Apollo, Relay...) and fits seamless in your GraphQL workflow.

To run a hello world server with graphql-yoga:

npm install graphql-yoga

Then run node server.js with this code in server.js:

import { GraphQLServer } from 'graphql-yoga'
// ... or using "require()"
// const { GraphQLServer } = require('graphql-yoga')
const typeDefs = `
type Query {
hello(name: String): String!
}
`;
const resolvers = {
Query: {
hello: (_, { name }) => `Hello ${name || 'World'}`,
},
};
const server = new GraphQLServer({ typeDefs, resolvers })
server.start(() => console.log('Server is running on localhost:4000'))

Client

A powerful JavaScript GraphQL client, designed to work well with React, React Native, Angular 2, or just plain JavaScript.

A simple and flexible JavaScript GraphQL client that works in all JavaScript environments (the browser, Node.js, and React Native) - basically a lightweight wrapper around fetch.

A JavaScript library for application development using cloud services, which supports GraphQL backend and React components for working with GraphQL data.

urql

A highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.

urql is a GraphQL client that exposes a set of helpers for several frameworks. It's built to be highly customisable and versatile so you can take it from getting started with your first GraphQL project all the way to building complex apps and experimenting with GraphQL clients.

  • Currently supports React, React Native, Preact, Svelte, and Vue, and is supported by GraphQL Code Generator.
  • Logical yet simple default behaviour and document caching, and normalized caching via @urql/exchange-graphcache
  • Fully customizable behaviour via "exchanges" (addon packages)

Facebook's framework for building React applications that talk to a GraphQL backend.

graphql-hooks

Minimal React hooks-first GraphQL client with a tiny bundle, SSR support and caching

  • 🥇 First-class hooks API
  • ⚖️ Tiny bundle: only 7.6kB (2.8 gzipped)
  • 📄 Full SSR support: see graphql-hooks-ssr
  • 🔌 Plugin Caching: see graphql-hooks-memcache
  • 🔥 No more render props hell
  • ⏳ Handle loading and error states with ease

Quickstart#

npm install graphql-hooks

First you'll need to create a client and wrap your app with the provider:

import { GraphQLClient, ClientContext } from 'graphql-hooks'
const client = new GraphQLClient({
url: '/graphql'
})
function App() {
return (
<ClientContext.Provider value={client}>
{/* children */}
</ClientContext.Provider>
)
}

Now in your child components you can make use of useQuery:

import { useQuery } from 'graphql-hooks'
const HOMEPAGE_QUERY = `query HomePage($limit: Int) {
users(limit: $limit) {
id
name
}
}`
function MyComponent() {
const { loading, error, data } = useQuery(HOMEPAGE_QUERY, {
variables: {
limit: 10
}
})
if (loading) return 'Loading...'
if (error) return 'Something Bad Happened'
return (
<ul>
{data.users.map(({ id, name }) => (
<li key={id}>{name}</li>
))}
</ul>
)
}

curl for GraphQL with autocomplete, subscriptions and GraphiQL. Also a dead-simple universal javascript GraphQL client.

A simple JavaScript GraphQL client that works in all JavaScript environments (the browser, Node.js, and React Native).

Tiny GraphQL client library using template strings.

A simple JavaScript GraphQL client,Let the *.gql file be used as a module through webpack loader.

An all purpose GraphQL client with view layer integrations for multiple frameworks in just 1.6kb.

Tools

One configuration for all your GraphQL tools (supported by most tools, editors & IDEs).

Coherent, zero-dependency, lazy, simple, GraphQL over WebSocket Protocol compliant server and client.

A set of utils for faster development of GraphQL tools (Schema and documents loading, Schema merging and more).

GraphQL code generator with flexible support for custom plugins and templates like Typescript (frontend and backend), React Hooks, resolvers signatures and more.

Real-Time with GraphQL for any GraphQL schema or transport.

An interactive in-browser GraphQL IDE.

A library of custom GraphQL scalar types for creating precise, type-safe GraphQL schemas.

GraphQLMiddleware

Split up your GraphQL resolvers in middleware functions.

GraphQL Middleware is a schema wrapper which allows you to manage additional functionality across multiple resolvers efficiently.

Features#

💡 Easy to use: An intuitive, yet familiar API that you will pick up in a second. 💪 Powerful: Allows complete control over your resolvers (Before, After). 🌈 Compatible: Works with any GraphQL Schema.

Example#

const { ApolloServer } = require('apollo-server')
const { makeExecutableSchema } = require('@graphql-tools/schema')
const typeDefs = `
type Query {
hello(name: String): String
bye(name: String): String
}
`
const resolvers = {
Query: {
hello: (root, args, context, info) => {
console.log(`3. resolver: hello`)
return `Hello ${args.name ? args.name : 'world'}!`
},
bye: (root, args, context, info) => {
console.log(`3. resolver: bye`)
return `Bye ${args.name ? args.name : 'world'}!`
},
},
}
const logInput = async (resolve, root, args, context, info) => {
console.log(`1. logInput: ${JSON.stringify(args)}`)
const result = await resolve(root, args, context, info)
console.log(`5. logInput`)
return result
}
const logResult = async (resolve, root, args, context, info) => {
console.log(`2. logResult`)
const result = await resolve(root, args, context, info)
console.log(`4. logResult: ${JSON.stringify(result)}`)
return result
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
const schemaWithMiddleware = applyMiddleware(schema, logInput, logResult)
const server = new ApolloServer({
schema: schemaWithMiddleware,
})
await server.listen({ port: 8008 })

An interface for building GraphQL language services for IDEs (diagnostics, autocomplete etc).

GraphQLShield

A GraphQL tool to ease the creation of permission layer.

GraphQL Shield helps you create a permission layer for your application. Using an intuitive rule-API, you'll gain the power of the shield engine on every request and reduce the load time of every request with smart caching. This way you can make sure your application will remain quick, and no internal data will be exposed.

import { rule, shield, and, or, not } from 'graphql-shield'
// Rules
const isAuthenticated = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.user !== null
},
)
const isAdmin = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.user.role === 'admin'
},
)
const isEditor = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.user.role === 'editor'
},
)
// Permissions
const permissions = shield({
Query: {
frontPage: not(isAuthenticated),
fruits: and(isAuthenticated, or(isAdmin, isEditor)),
customers: and(isAuthenticated, isAdmin),
},
Mutation: {
addFruitToBasket: isAuthenticated,
},
Fruit: isAuthenticated,
Customer: isAdmin,
})
// Server
const server = new GraphQLServer({
typeDefs,
resolvers,
middlewares: [permissions],
context: (req) => ({
...req,
user: getUser(req),
}),
})

Compare schemas, validate documents, find breaking changes, find similar types, schema coverage, and more.

GraphQL-ESLint integrates GraphQL AST in the ESLint core (as a parser).

A command line tool for common GraphQL development workflows.

builds a powerful, extensible and performant GraphQL API from a PostgreSQL schema in seconds; saving you weeks if not months of development time.

GraphQL Mesh allows you to use GraphQL query language to access data in remote APIs that don't run GraphQL (and also ones that do run GraphQL). It can be used as a gateway to other services, or run as a local GraphQL schema that aggregates data from remote APIs.

GraphQL Modules lets you separate your backend implementation to small, reusable, easy-to-implement and easy-to-test pieces.

GiraphQL

A plugin based schema builder for creating code-first GraphQL schemas in typescript

GiraphQL makes writing type-safe schemas simple, and works without a code generator, build process, or extensive manual type definitions.

import { ApolloServer } from "apollo-server"
import SchemaBuilder from "@giraphql/core"
const builder = new SchemaBuilder({})
builder.queryType({
fields: t => ({
hello: t.string({
args: {
name: t.arg.string({}),
},
resolve: (parent, { name }) => `hello, ${name || "World"}`,
}),
}),
})
new ApolloServer({
schema: builder.toSchema({}),
}).listen(3000)

Generate REST API from your GraphQL API.

Tools#

GraphQL code generator with flexible support for custom plugins and templates like Typescript (frontend and backend), React Hooks, resolvers signatures and more.

Generate types for GraphQL queries in TypeScript, Swift, golang, C#, C++, and more.

Schemathesis

A modern API testing tool for web applications built with Open API and GraphQL specifications.

Install Schemathesis via pip:

pip install schemathesis

Then, create a file test_api.py with the content below and replace the URL value with your own GraphQL endpoint URL:

from hypothesis import settings
import schemathesis
URL = "https://your.app.com/graphql"
schema = schemathesis.graphql.from_url(URL)
@schema.parametrize()
@settings(deadline=None)
def test_api(case):
response = case.call()
case.validate_response(response)

Then run pytest test_api.py. Note that you can write your app in any programming language; the tool will communicate with it over HTTP.

Schemathesis will generate valid queries automatically based on the schema and will minimize failing cases. For example, running the code above against https://bahnql.herokuapp.com/graphql uncovers that running the { search(searchTerm: "") { stations { name } } } query leads to a server error:

{"errors":[{"message":"Cannot read property \'city\' of undefined","locations":[{"line":1,"column":28}],"path":["search","stations"]}],"data":null}

Services#

An alternative to Postman that supports editing GraphQL queries directly and autoload your GraphQL schema.

A cloud service for monitoring the performance and usage of your GraphQL backend.

Fully managed GraphQL service with realtime subscriptions, offline programming & synchronization, and enterprise security features as well as fine grained authorization controls.

A Java library that can expose a JPA annotated data model as a GraphQL service over any relational database.

Create an instant GraphQL backend by importing a gql schema. The database will create relations and indexes for you, so you'll be ready to query in seconds, without writing any database code. Serverless pricing, free to get started.

A BaaS (Backend as a Service) that sets you up with a GraphQL backend as well as tools for content editors to work with the stored data.

Hasura connects to your databases & microservices and instantly gives you a production-ready GraphQL API.

A headless CMS (Content Management System) that combines powerful content personalisation and scheduling capabilities with a modern content editing experience and a blazing fast GraphQL/REST content delivery API.

A GraphQL analaytics and monitoring Service to find functional and performance issues.

An HTTP Client that supports editing GraphQL queries.

A BaaS (Backend as a Service) providing a GraphQL backend for your applications with a powerful web ui for managing your database and stored data.

A SaaS (Software as a Service) content management system that allows you to create your content with powerful editing tools and access it from anywhere with a GraphQL or REST API.

Want to improve this page? See the docs here.