🎬 That's a Wrap for GraphQLConf 2024! • Watch the Videos • Check out the recorded talks and workshops

Code Using GraphQL

Sort by:
GraphQL.js
The reference implementation of the GraphQL specification, designed for running GraphQL in a Node.js environment.
Last release 2 months ago20kMIT License
README

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 rootValue = { hello: () => "Hello world!" }
 
var source = "{ hello }"
 
graphql({ schema, source, rootValue }).then(response => {
  console.log(response)
})
Apollo Server
A GraphQL server from Apollo that works with any Node.js HTTP framework
Last release 2 months ago14kMIT License
README

To run a hello world server with Apollo Server:

npm install @apollo/server graphql

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

import { ApolloServer } from "@apollo/server"
import { startStandaloneServer } from "@apollo/server/standalone"
 
const server = new ApolloServer({
  typeDefs,
  resolvers,
})
 
const { url } = await startStandaloneServer(server)
 
console.log(`🚀 Server ready at ${url}`)

Apollo Server has a built in standalone HTTP server and middleware for Express, and has an framework integration API that supports all Node.js HTTP server frameworks and serverless environments via community integrations.

Apollo Server has a plugin API, integration with Apollo Studio, and performance and security features such as caching, automatic persisted queries, and CSRF prevention.

99designs/gqlgen
Go generate based graphql server library.
Last release 3 weeks ago10kMIT License
graphql-go
An implementation of GraphQL for Go / Golang.
Last release 1 year ago10kMIT License
API Platform
API Platform is a fully-featured, flexible and extensible API framework built on top of Symfony.
Last release 3 months ago9kMIT License
README

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.

graphql-yoga
GraphQL Yoga is a batteries-included cross-platform GraphQL over HTTP spec-compliant GraphQL Server using Envelop and GraphQL Tools.
Last release 2 months ago8kMIT License
README
  • Built around the Fetch API Request & Response objects
  • GraphQL over HTTP compliant
  • Extensible GraphQL Engine powered by Envelop
  • GraphQL Subscriptions over HTTP
  • Handle file uploads with GraphQL
  • Integrates with AWS Lambda, Cloudflare Workers, Deno, Express, Next.js, SvelteKit, and more.

To run a hello world server with graphql-yoga:

npm install graphql-yoga graphql

Then create a server using the createServer import:

import { createServer } from "http"
import { createSchema, createYoga } from "graphql-yoga"
 
createServer(
  createYoga({
    schema: createSchema({
      typeDefs: /* GraphQL */ `
        type Query {
          hello: String
        }
      `,
      resolvers: {
        Query: {
          hello: () => "Hello Hello Hello",
        },
      },
    }),
  }),
).listen(4000, () => {
  console.info("GraphQL Yoga is listening on http://localhost:4000/graphql")
})

Depending on your deployment target, you may need to use an additional library. See the documentation for further details.

Graphene
A Python library for building GraphQL APIs.
Last release 1 week ago8kMIT License
README

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.

graphql-java
A Java library for building GraphQL APIs.
Last release 1 month ago6kMIT License
README

See the Getting Started tutorial on the GraphQL Java website.

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}";
 
        SchemaParser schemaParser = new SchemaParser();
        TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
 
        RuntimeWiring runtimeWiring = newRuntimeWiring()
                .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 further information.

graphql-dotnet
GraphQL for .NET
Last release 2 days ago6kMIT License
README
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);
  }
}
graphql-rust/juniper
GraphQL server library for Rust
Last release 3 months ago6kOther
graphql-ruby
A Ruby library for building GraphQL APIs.
Last release 3 years ago5kMIT License
README

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
  field :hello, String
 
  def hello
    "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.

Hot Chocolate
Hot Chocolate is an open-source GraphQL Server for .NET
Last release 2 days ago5kMIT License
README

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";
}
graph-gophers/graphql-go
GraphQL server with a focus on ease of use.
Last release 1 year ago5kBSD 2-Clause "Simplified" License
graphql-php
A PHP port of GraphQL reference implementation
Last release 1 day ago5kMIT License
absinthe
GraphQL implementation for Elixir.
Last release 3 months ago4kOther
Strawberry
Strawberry is a Python library for implementing code first GraphQL servers using modern Python features like type hints.
Last release 6 days ago4kMIT License
README

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.

WPGraphQL
A free, open-source WordPress plugin that provides an extendable GraphQL schema and API for any WordPress site
Last release 1 month ago4kGNU General Public License v3.0
Async-graphql
Async-graphql is a high-performance server-side library that supports all GraphQL specifications.
3kApache License 2.0
README
 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
    }
 }
Lighthouse
A GraphQL server for Laravel
Last release 1 month ago3kMIT License
Domain Graph Service (DGS) Framework
The DGS Framework (Domain Graph Service) is a GraphQL server framework for Spring Boot, developed by Netflix.
Last release 1 week ago3kApache License 2.0
README

The DGS Framework (Domain Graph Service) is a GraphQL server framework for Spring Boot, developed by Netflix.

Features include:

  • Annotation based Spring Boot programming model
  • Test framework for writing query tests as unit tests
  • Gradle Code Generation plugin to create types from schema
  • Easy integration with GraphQL Federation
  • Integration with Spring Security
  • GraphQL subscriptions (WebSockets and SSE)
  • File uploads
  • Error handling
  • Many extension points

See DGS Framework Getting Started for how to get started.

Mercurius
Mercurius is a flexible and extendible GraphQL adapter for Fastify, a blazing-fast web framework with the least overhead and a powerful plugin architecture.
Last release 1 week ago2kMIT License
README

To run an hello world script with mercurius:

npm install fastify mercurius

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

const Fastify = require("fastify")
const mercurius = require("mercurius")
 
const schema = `
  type Query {
    hello(name: String): String!
  }
`
 
const resolvers = {
  Query: {
    hello: async (_, { name }) => `hello ${name || "world"}`,
  },
}
 
const app = Fastify()
app.register(mercurius, {
  schema,
  resolvers,
})
 
app.listen(3000)
 
// Call IT!
// curl 'http://localhost:3000/graphql' \
//  -H 'content-type: application/json' \
//  --data-raw '{"query":"{ hello(name:\"Marcurius\") }" }'
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.
Last release 7 months ago2kBSD 3-Clause "New" or "Revised" License
README

Ariadne can be installed with pip:

$ pip install ariadne

Minimal “Hello world” server example:

from ariadne import ObjectType, gql, make_executable_schema
from ariadne.asgi import GraphQL
 
type_defs = gql(
    """
    type Query {
        hello: String!
    }
    """
)
 
query_type = ObjectType("Query")
 
@query_type.field("hello")
def resolve_hello(*_):
    return "Hello world!"
 
schema = make_executable_schema(type_defs, query_type)
 
app = GraphQL(schema, debug=True)

Run the server with uvicorn:

$ pip install uvicorn
$ uvicorn example:app
Sangria
A Scala GraphQL library that supports Relay.
Last release 4 days ago2kApache License 2.0
README

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
lacinia
A full implementation of the GraphQL specification that aims to maintain external compliance with the specification.
2kOther
graphql-kotlin
A set of libraries for running GraphQL client and server in Kotlin.
Last release 14 hours ago2kApache License 2.0
README

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.

GraphQL-WS
Coherent, zero-dependency, lazy, simple, GraphQL over WebSocket Protocol compliant server and client.
Last release 7 months ago2kMIT License
samsarahq/thunder
A GraphQL implementation with easy schema building, live queries, and batching.
2kMIT License
Spring for GraphQL
Spring for GraphQL provides support for Spring applications built on GraphQL Java.
Last release 4 days ago2kApache License 2.0
README

Spring for GraphQL provides support for Spring applications built on GraphQL Java. See the official Spring guide for how to build a GraphQL service in 15 minutes.

  • It is a joint collaboration between the GraphQL Java team and Spring engineering.
  • Our shared philosophy is to provide as little opinion as we can while focusing on comprehensive support for a wide range of use cases.
  • It aims to be the foundation for all Spring, GraphQL applications.

Features:

  • Server handling of GraphQL requests over HTTP, WebSocket, and RSocket.
  • An annotation-based programming model where @Controller components use annotations to declare handler methods with flexible method signatures to fetch the data for specific GraphQL fields. For example:
@Controller
public class GreetingController {
 
    @QueryMapping
    public String hello() {
        return "Hello, world!";
    }
 
}
  • Client support for executing GraphQL requests over HTTP, WebSocket, and RSocket.
  • Dedicated support for testing GraphQL requests over HTTP, WebSocket, and RSocket, as well as for testing directly against a server.

To get started, check the Spring GraphQL starter on https://start.spring.io and the samples in this repository.

GraphQL Spring Boot
GraphQL Spring Boot from GraphQL Java Kickstart
Last release 10 months ago2kMIT License
README

The GraphQL Spring Boot turns any Spring Boot application into a GraphQL Server

Started includes features such as:

See GraphQL Java Kickstart Getting Started for how to get started.

Siler
Siler is a PHP library powered with high-level abstractions to work with GraphQL.
Last release 3 years ago1kMIT License
README

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.

Caliban
Caliban is a functional library for building GraphQL servers and clients in Scala. It offers minimal boilerplate and excellent interoperability.
Last release 1 month ago1kApache License 2.0
README

An example of a simple GraphQL schema and query with caliban:

import caliban._
import caliban.schema.Schema.auto._
 
// schema
case class Query(hello: String)
 
// resolver
val resolver = RootResolver(Query("Hello world!"))
 
val api = graphQL(resolver)
 
for {
  interpreter <- api.interpreter
  result      <- interpreter.execute("{ hello }")
} yield result
Agoo
A high performance web server with support for GraphQL. Agoo strives for a simple, easy to use API for GraphQL.
1kMIT License
README
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
graphql-net
Convert GraphQL to IQueryable
1kMIT License
graphql-elixir
An Elixir implementation of Facebook's GraphQL.
Last release 8 years ago1kOther
Tartiflette
A Python 3.6+ (asyncio) library for building GraphQL APIs.
Last release 2 years ago1kMIT License
README

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.

GraphQLBundle
A GraphQL server for Symfony
Last release 1 month ago1kMIT License
Jimmer
A revolutionary ORM framework for both java and kotlin, it also provides specialized API for rapid development of Spring GraphQL-based applications.
Last release 23 hours ago1kApache License 2.0
README

Introduce

  1. SpringBoot has introduced Spring GraphQL since 2.7. Jimmer provides specialized API for rapid development of Spring GraphQL-based applications.

  2. Support two APIs: Java API & kotlin API.

  3. Powerful and GraphQL friendly caching support.

  4. Faster than other popular ORM solutions, please see the benchmark: https://babyfish-ct.github.io/jimmer/docs/benchmark/

  5. More powerful than other popular ORM solutions.

    Three aspects should be considered in ORM design:

    a. Query. b. Update. c. Cache.

    Each aspect is aimed at object trees with arbitrary depth rather than simple objects. This distinctive design brings convenience unmatched by other popular solutions.

Links

graphql-go-tools
A collection of tools for building GraphQL Servers, Gateways, Proxy Servers and Middleware in Go.
Last release 4 months ago1kMIT License
README

graphql-go-tools implements all basic blocks for building GraphQL Servers, Gateways and Proxy Servers. From lexing, parsing, validation, normalization, all the way up to query planning and execution.

It can also be understood as a GraphQL Compiler, with the ability to add your own backends. Just by implementing a few interfaces, you’re able to teach the compiler how to talk GraphQL to any backend.

The following backends are already implemented: GraphQL, with support for Apollo Federation / Supergraph. Databases: PostgreSQL, MySQL, SQLite, CockroachDB, MongoDB, SQLServer, OpenAPI / REST and Kafka.

To get a sense on how to implement a new backend, check out the Static Data Source, as it’s the simplest one.

It’s used in production by many enterprises for multiple years now, battle tested and actively maintained.

ocaml-graphql-server
GraphQL server library for OCaml and Reason
Last release 2 years ago1kMIT License
GraphQLite
GraphQLite is a library that offers an annotations-based syntax for GraphQL schema definition.
Last release 7 months ago1kMIT License
README

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…

Graphiti
Swift library for building GraphQL schemas/types fast, safely and easily.
Last release 3 months ago1kMIT License
graphql-relay-go
A Go/Golang library to help construct a graphql-go server supporting react-relay.
424MIT License
Entity GraphQL
A GraphQL library for .NET Core. Easily expose you data model as a GraphQL API or bring together multiple data sources into a single GraphQL schema.
Last release 1 day ago416MIT License
README
// expose an existing data model with ASP.NET & EF Core
public class Startup {
  public void ConfigureServices(IServiceCollection services)
  {
      services.AddDbContext<DemoContext>();
      // Auto build a schema from DemoContext. Alternatively you can build one from scratch
      services.AddGraphQLSchema<DemoContext>(options =>
      {
          // modify the schema (add/remove fields or types), add other services
      });
  }
 
  public void Configure(IApplicationBuilder app, DemoContext db)
  {
      app.UseRouting();
      app.UseEndpoints(endpoints =>
      {
          // defaults to /graphql endpoint
          endpoints.MapGraphQL<DemoContext>();
      });
  }
}
Morpheus GraphQL
A Haskell library for building GraphQL APIs.
Last release 4 months ago409MIT License
README

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.

GraphQL-SSE
Zero-dependency, HTTP/1 safe, simple, GraphQL over Server-Sent Events Protocol server and client.
Last release 7 months ago385MIT License
Railt
A PHP GraphQL Framework.
Last release 5 years ago360MIT License
Gato GraphQL
Interact with all your data in WordPress
Last release 2 weeks ago358GNU General Public License v2.0
Mu-Haskell with Mu-GraphQL
A Haskell library for building microservices (gRPC, HTTP) and GraphQL APIs.
Last release 3 years ago333Apache License 2.0
README

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!

graphql-erlang
GraphQL implementation in Erlang.
Last release 6 years ago313Other
GraphQL-HTTP
Simple, pluggable, zero-dependency, GraphQL over HTTP spec compliant server, client and audit suite.
Last release 6 months ago313MIT License
KGraphQL
KGraphQL is a Kotlin implementation of GraphQL. It provides a rich DSL to set up the GraphQL schema.
Last release 1 year ago301MIT License
README

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.

graphql-clj
A Clojure library that provides a GraphQL implementation.
285Eclipse Public License 1.0
README

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 }")
graphql-relay-php
A library to help construct a graphql-php server supporting react-relay.
Last release 3 years ago271BSD 3-Clause "New" or "Revised" License
Rails GraphQL
A Fresh new GraphQL server for Rails applications, with a focus on natural and Ruby-like DSL
Last release 5 months ago174MIT License
README
require 'rails-graphql'
 
class GraphQL::AppSchema < GraphQL::Schema
  query_fields do
    field(:hello).resolve { 'Hello World!' }
  end
end
 
puts GraphQL::AppSchema.execute('{ hello }')

Less is more! Please check it out the docs.

alumbra
A set of reusable GraphQL components for Clojure conforming to the data structures given in alumbra.spec.
Last release 7 years ago148MIT License
README
(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"}]}}}
ghql
General purpose GraphQL R client
Last release 4 years ago146Other
GraphZahl
Swift library for writing Declarative, Type-Safe GraphQL APIs with Zero Boilerplate.
Last release 3 years ago143MIT License
ballerina-graphql
The Ballerina Standard Library Package for write GraphQL services.
Last release 2 months ago140Apache License 2.0
README

To run a ballerina-graphql hello world server:

  • Download and install Ballerina Language
  • Then run bal run graphql_service.bal to run the service, with this code in the graphql_service.bal file:
import ballerina/graphql;
 
service /graphql on new graphql:Listener(9090) {
    resource function get hello() returns string {
        return "Hello, world!";
    }
}

Features

  • Built with Ballerina service and listener model, which are first-class citizens in Ballerina
  • Supports subscriptions over websocket (No additional libraries needed)
  • Supports file upload
  • Built-in GraphiQL client
graphql-calculator
A lightweight graphql calculation engine.
Last release 3 years ago109Apache License 2.0
README

GraphQL Calculator is a lightweight graphql calculation engine, which is used to alter execution behavior of graphql query.

Here are some examples on how to use GraphQL Calculator on graphql query.

query basicMapValue($userIds: [Int]) {
  userInfoList(userIds: $userIds) {
    id
    age
    firstName
    lastName
    fullName: stringHolder @map(mapper: "firstName + lastName")
  }
}
 
query filterUserByAge($userId: [Int]) {
  userInfoList(userIds: $userId) @filter(predicate: "age>=18") {
    userId
    age
    firstName
    lastName
  }
}
 
query parseFetchedValueToAnotherFieldArgumentMap($itemIds: [Int]) {
  itemList(itemIds: $itemIds) {
    # save sellerId as List<Long> with unique name "sellerIdList"
    sellerId @fetchSource(name: "sellerIdList")
    name
    saleAmount
    salePrice
  }
 
  userInfoList(userIds: 1)
    # transform the argument of "userInfoList" named "userIds" according to expression "sellerIdList" and expression argument,
    # which mean replace userIds value by source named "sellerIdList"
    @argumentTransform(
      argumentName: "userIds"
      operateType: MAP
      expression: "sellerIdList"
      dependencySources: ["sellerIdList"]
    ) {
    userId
    name
    age
  }
}

See graphql-calculator README for more information.

MicroProfile GraphQL
MP GraphQL is a code-first specification for building GraphQL applications. It uses annotations and design patterns similar to JAX-RS to enable rapid development.
Last release 2 years ago100Apache License 2.0
README

MicroProfile GraphQL is a GraphQL server and client specification for building GraphQL applications. It’s unique annotation-based API approach enables rapid application development. Applications coded to the MP GraphQL APIs are portable, and can be deployed into Java server runtimes such as Open Liberty, Quarkus, Helidon and Wildfly. This means that your applications can make use of other Jakarta and MicroProfile technologies.

MP GraphQL features include:

  • Annotation-based APIs
  • Integration with Jakarta CDI
  • Type-safe and dynamic client APIs
  • Exception handling
  • Easy integration with Jakarta and MicroProfile technologies

Want to get started? Check out these resources:

Or these videos:

Pylon
A code-first framework for GraphQL API development, where your schema reflects your functionality. Run npm create pylon@latest to get started.
Last release 1 week ago97Apache License 2.0
README
  1. Create
npm create pylon@latest
  1. Develop

Example service:

import { app } from "@getcronit/pylon"
 
class User {
  name: string
  email: string
  constructor(name: string, email: string) {
    this.name = name
    this.email = email
  }
}
 
const users = [
  new User("Alice", "alice@example.com"),
  new User("Bob", "bob@example.com"),
  new User("Charlie", "charlie@example.com"),
]
 
export const graphql = {
  Query: {
    users,
    user: (name: string) => {
      return users.find(user => user.name === name)
    },
  },
  Mutation: {
    addUser: (name: string, email: string) => {
      const user = new User(name, email)
      users.push(user)
      return user
    },
  },
}
 
export default app
  1. Query
query User {
  user(name: "Alice") {
    name
    email
  }
}
 
query Users {
  users {
    name
    email
  }
}
 
mutation AddUser {
  addUser(name: "Corina", email: "corina@example.com") {
    name
    email
  }
}
gorm-graphql
An automatic GraphQL schema generator for GORM
Last release 10 months ago80Apache License 2.0
README

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.

appointy/jaal
Develop spec compliant GraphQL servers in Go.
Last release 4 years ago77MIT License
graphql-perl
A Perl port of GraphQL reference implementation
71Unknown
README
GQL
GQL is a Groove library for GraphQL
Last release 1 year ago49Apache License 2.0
NGraphQL
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.
43MIT License
GraPHPinator
A GraphQL implementation for modern PHP. Includes features from latest draft, middleware directives and modules with extra functionality.
Last release 1 week ago40MIT License
README

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.
EGGQL
Easy to use, complete Go implementation of GraphQL. Simple and schema-less.
37MIT License
README

The purpose of Eggql is to make it as simple as possible to create a GraphQL server. You don’t need to create GraphQL schema (though you can view the schema that is created if interested). It is currently in beta release but is a complete implementation of a GraphQL server apart from subscriptions.

Just to be clear it supports all of these GraphQL features: arguments (including defaults), objects/lists/enums/input/interface/union types, aliases, fragments, variables, directives, mutations, inline fragments, descriptions, introspection and custom scalars.

Tests (jMeter) show that it is as fast or faster than other Go implementations for simple queries. We’re working on enhancements for performance including caching, data-loader, complexity-limits, etc.

To run an eggql hello world server just build and run this Go program:

package main

import "github.com/andrewwphillips/eggql"

func main() {
	http.Handle("/graphql", eggql.New(struct{ Message string }{Message: "hello, world"}))
	http.ListenAndServe(":80", nil)
}

This creates a root Query object with a single message field. To test it send a query with curl:

$ curl -XPOST -d '{"query": "{ message }"}' localhost:80/graphql

and you will get this response:

{
  "data": {
    "message": "hello, world"
  }
}
graphqld
A GraphQL implementation for the D Programming Language.
Last release 5 months ago35GNU Lesser General Public License v3.0
GraphQLBox server
An extensible GraphQL server with modules for caching, request parsing, debugging, subscriptions and more...
25MIT License
README

The example below installs and initializes the GraphQLBox server with a persisted cache and debugging enabled.

npm install @graphql-box/core @graphql-box/server @graphql-box/client @graphql-box/request-parser @graphql-box/cache-manager @graphql-box/debug-manager @graphql-box/execute @graphql-box/helpers @cachemap/core @cachemap/reaper @cachemap/redis @cachemap/constants @cachemap/types
import Cachemap from "@cachemap/core"
import redis from "@cachemap/redis"
import reaper from "@cachemap/reaper"
import CacheManager from "@graphql-box/cache-manager"
import Client from "@graphql-box/client"
import DebugManager from "@graphql-box/debug-manager"
import Execute from "@graphql-box/execute"
import RequestParser from "@graphql-box/request-parser"
import Server from "@graphql-box/server"
import { makeExecutableSchema } from "@graphql-tools/schema"
import { performance } from "perf_hooks"
import { schemaResolvers, schemaTypeDefs } from "./schema"
import logger from "./logger"
 
const schema = makeExecutableSchema({
  typeDefs: schemaTypeDefs,
  resolvers: schemaResolvers,
})
 
const server = new Server({
  client: new Client({
    cacheManager: new CacheManager({
      cache: new Cachemap({
        name: "server-cache",
        reaper: reaper({ interval: 300000 }),
        store: redis(/* configure */),
      }),
      cascadeCacheControl: true,
      typeCacheDirectives: {
        // Add any type specific cache control directives in the format:
        // TypeName: "public, max-age=3",
      },
    }),
    debugManager: new DebugManager({
      environment: "server",
      log: (...args) => {
        logger.log(...args)
      },
      name: "SERVER",
      performance,
    }),
    requestManager: new Execute({ schema }),
    requestParser: new RequestParser({ schema }),
  }),
})
 
// Meanwhile... somewhere else in your code
 
app.use("api/graphql", graphqlServer.request())
Graphene Django CRUDDALS
Turn your Django-models into a complete GraphQL API with all CRUD operations
12Apache License 2.0
README

You can install the package with pip

pip install graphene-django-cruddals

To use it, simply create a new class that inherits “DjangoModelCruddals” Suppose we have the following models.

from django.db import models
 
 
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    is_active = models.BooleanField(default=True)

Then we can create a complete CRUD+DALS for the models Question with the following code

from graphene_django_cruddals import DjangoModelCruddals
 
class CruddalsQuestion(DjangoModelCruddals):
    class Meta:
        model = Question

Now you can use the schema that was generated for you,

schema = CruddalsQuestion.Schema

or use in your existing schema root Query and Mutation

class Query(
    # ... your others queries
    CruddalsQuestion.Query,
    graphene.ObjectType,
):
    pass
 
 
class Mutation(
    # ... your others mutations
    CruddalsQuestion.Mutation,
    graphene.ObjectType,
):
    pass
 
 
schema = graphene.Schema( query=Query, mutation=Mutation, )

That’s it! You can test in graphiql or any other client that you use to test your GraphQL APIs..

Find more information in the official documentation.

graphql-w-persistent
Complete set of library tools to abstract relational database schemas with SQL, query with GraphQL, and return GraphQL results
10Unknown
README

One time setup: build schema, deploy as microservice or within server, query SQL database with GraphQL!

Django Graphbox
Package for easy building a GraphQL API with basic CRUD operations for Django models.
Last release 7 months ago10MIT License
README

A Quickstart for Django Graphbox:

  1. Install the package:
pip install django-graphbox
  1. Create a new Django project:
django-admin startproject myproject
  1. Create a new Django app:
cd myproject
python manage.py startapp myapp
  1. Define your Django models in myapp/models.py:
from django.db import models
 
class MyModel(models.Model):
    name = models.CharField(max_length=100)
  1. Create and run migrations:
python manage.py makemigrations
python manage.py migrate
  1. Configure and Build your GraphQL Schema in myapp/schema.py:
from django_graphbox.builder import SchemaBuilder
from myapp.models import MyModel
 
builder = SchemaBuilder()
builder.add_model(MyModel)
 
query_class = builder.build_schema_query()
mutation_class = builder.build_schema_mutation()
  1. Create a main Schema in myproject/schema.py (In this main schema you can add your own queries and mutations):
import graphene
from myapp.schema import query_class, mutation_class
 
class Query(query_class, graphene.ObjectType):
    pass
 
class Mutation(mutation_class, graphene.ObjectType):
    pass
 
schema = graphene.Schema(query=Query, mutation=Mutation)
  1. Add the GraphQL view to your myproject/urls.py:
from django.urls import path
from graphene_file_upload.django import FileUploadGraphQLView
from django.views.decorators.csrf import csrf_exempt
from myproject.schema import schema
 
urlpatterns = [
    path('graphql/', csrf_exempt(FileUploadGraphQLView.as_view(graphiql=True, schema=schema))),
]
  1. Run the server:
python manage.py runserver
  1. Open the GraphiQL interface at http://localhost:8000/graphql and start querying your API!

You can find advanced examples with authentication, filters, validations and more on GitHub or pypi.

serge
Use GraphQL to define your Domain Model for CQRS/ES and let serge generate code to handle GraphQL requests.
5GNU General Public License v3.0