Convert Figma logo to code with AI

graphql-java logographql-java

GraphQL Java implementation

6,098
1,115
6,098
27

Top Related Projects

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

A reference implementation of GraphQL for JavaScript

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

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Awesome list of GraphQL

9,867

An implementation of GraphQL for Go / Golang

Quick Overview

GraphQL Java is a Java implementation of GraphQL, a query language for APIs. It allows developers to create flexible and efficient GraphQL servers in Java applications, providing a robust foundation for building GraphQL APIs.

Pros

  • Comprehensive implementation of the GraphQL specification
  • Highly customizable and extensible
  • Active community and regular updates
  • Excellent documentation and examples

Cons

  • Steeper learning curve compared to REST APIs
  • Can be complex to set up for larger projects
  • Performance considerations for deeply nested queries
  • Limited built-in security features

Code Examples

  1. Defining a GraphQL schema:
GraphQLSchema schema = GraphQLSchema.newSchema()
    .query(GraphQLObjectType.newObject()
        .name("Query")
        .field(GraphQLFieldDefinition.newFieldDefinition()
            .name("hello")
            .type(GraphQLString)
            .dataFetcher(environment -> "Hello, GraphQL!")
        )
        .build())
    .build();
  1. Executing a GraphQL query:
GraphQL graphQL = GraphQL.newGraphQL(schema).build();
ExecutionResult result = graphQL.execute("{hello}");
System.out.println(result.getData().toString());
  1. Creating a custom scalar type:
GraphQLScalarType dateScalar = GraphQLScalarType.newScalar()
    .name("Date")
    .description("Date custom scalar type")
    .coercing(new Coercing<Date, String>() {
        @Override
        public String serialize(Object dataFetcherResult) {
            return ((Date) dataFetcherResult).toInstant().toString();
        }

        @Override
        public Date parseValue(Object input) {
            return Date.from(Instant.parse((String) input));
        }

        @Override
        public Date parseLiteral(Object input) {
            return Date.from(Instant.parse(((StringValue) input).getValue()));
        }
    })
    .build();

Getting Started

To use GraphQL Java in your project, add the following dependency to your build.gradle file:

dependencies {
    implementation 'com.graphql-java:graphql-java:19.2'
}

For Maven, add this to your pom.xml:

<dependency>
    <groupId>com.graphql-java</groupId>
    <artifactId>graphql-java</artifactId>
    <version>19.2</version>
</dependency>

Then, create a simple GraphQL schema and execute a query:

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;

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 = 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();
        System.out.println(build.execute("{hello}").getData().toString());
    }
}

This will output: {hello=world}

Competitor Comparisons

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

Pros of Apollo Server

  • Easier setup and configuration for Node.js environments
  • Extensive documentation and community support
  • Built-in features like caching, subscriptions, and file uploads

Cons of Apollo Server

  • Limited to JavaScript/TypeScript ecosystems
  • May have higher memory usage for large-scale applications
  • Less flexibility for custom implementations compared to GraphQL Java

Code Comparison

Apollo Server:

const { ApolloServer } = require('apollo-server');
const typeDefs = gql`
  type Query {
    hello: String
  }
`;
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};
const server = new ApolloServer({ typeDefs, resolvers });

GraphQL Java:

GraphQLSchema schema = GraphQLSchema.newSchema()
    .query(newObject()
        .name("Query")
        .field(newFieldDefinition()
            .name("hello")
            .type(GraphQLString)
            .dataFetcher(environment -> "Hello world!")))
    .build();

Apollo Server provides a more concise setup, especially for JavaScript developers, while GraphQL Java offers more granular control over schema definition and execution. Apollo Server is ideal for rapid development in Node.js environments, whereas GraphQL Java is better suited for Java-based applications requiring deep customization.

A reference implementation of GraphQL for JavaScript

Pros of graphql-js

  • Developed and maintained by the GraphQL Foundation, ensuring alignment with the latest GraphQL specifications
  • Extensive ecosystem and community support in the JavaScript/Node.js environment
  • Seamless integration with popular JavaScript frameworks and libraries

Cons of graphql-js

  • Limited to JavaScript/Node.js environments, lacking cross-language support
  • May have performance limitations for high-load applications compared to compiled languages

Code Comparison

graphql-js:

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

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

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

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

graphql-java:

GraphQLSchema schema = GraphQLSchema.newSchema()
    .query(newObject()
        .name("Query")
        .field(newFieldDefinition()
            .name("hello")
            .type(GraphQLString)
            .dataFetcher(environment -> "Hello world!")))
    .build();

GraphQL graphQL = GraphQL.newGraphQL(schema).build();
ExecutionResult result = graphQL.execute("{ hello }");
System.out.println(result.getData());

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

Pros of graphql-engine

  • Provides a ready-to-use GraphQL server with automatic CRUD operations
  • Offers real-time subscriptions out of the box
  • Includes a user-friendly web interface for schema management and API exploration

Cons of graphql-engine

  • Less flexible for custom business logic compared to graphql-java
  • Primarily designed for PostgreSQL, limiting database options
  • Steeper learning curve for developers unfamiliar with Hasura's ecosystem

Code Comparison

graphql-java:

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

graphql-engine:

tables:
  - table:
      schema: public
      name: users
    select_permissions:
      - role: user
        permission:
          columns: [id, name, email]
          filter: {}

The graphql-java example shows how to create and execute a GraphQL schema programmatically, while the graphql-engine example demonstrates how to define table permissions declaratively using YAML configuration.

graphql-java offers more flexibility for custom implementations, whereas graphql-engine provides a higher-level abstraction for rapid development of GraphQL APIs with built-in features like permissions and real-time subscriptions.

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Pros of Prisma

  • Offers a more user-friendly, type-safe database toolkit with auto-generated queries
  • Provides seamless database migrations and introspection capabilities
  • Supports multiple databases (PostgreSQL, MySQL, SQLite, etc.) out of the box

Cons of Prisma

  • Less flexible for complex GraphQL schema designs compared to GraphQL Java
  • Steeper learning curve for developers familiar with traditional ORM approaches
  • May introduce additional complexity in projects that don't require its full feature set

Code Comparison

Prisma schema definition:

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

GraphQL Java schema definition:

TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
typeRegistry.add(SchemaParser.parse("
  type User {
    id: ID!
    email: String!
    name: String
    posts: [Post!]!
  }
"));

Prisma focuses on defining database models, while GraphQL Java directly defines GraphQL types. Prisma generates database queries and resolvers automatically, whereas GraphQL Java requires manual implementation of resolvers and data fetching logic.

Awesome list of GraphQL

Pros of awesome-graphql

  • Comprehensive resource collection: Offers a curated list of GraphQL-related tools, libraries, and resources across multiple languages and platforms
  • Community-driven: Regularly updated with contributions from the GraphQL community, ensuring up-to-date information
  • Learning resource: Serves as an excellent starting point for developers new to GraphQL

Cons of awesome-graphql

  • Not a functional library: Unlike graphql-java, it doesn't provide actual GraphQL implementation
  • Potential information overload: The extensive list of resources may be overwhelming for beginners

Code comparison

As awesome-graphql is a curated list and not a functional library, a direct code comparison is not applicable. However, here's an example of how the two repositories differ in content:

awesome-graphql (README.md):

## Tools
- [GraphiQL](https://github.com/graphql/graphiql) - An in-browser IDE for exploring GraphQL.
- [GraphQL Playground](https://github.com/prisma/graphql-playground) - GraphQL IDE for better development workflows.

graphql-java (Example usage):

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

The comparison highlights that while awesome-graphql provides a comprehensive list of GraphQL resources, graphql-java offers a functional Java implementation of GraphQL.

9,867

An implementation of GraphQL for Go / Golang

Pros of graphql-go

  • Written in Go, offering better performance and lower resource usage
  • Simpler API design, making it easier to integrate into Go projects
  • Lightweight and has fewer dependencies

Cons of graphql-go

  • Less mature ecosystem compared to graphql-java
  • Fewer features and extensions available out-of-the-box
  • Smaller community and less documentation

Code Comparison

graphql-go:

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

graphql-java:

GraphQLSchema schema = GraphQLSchema.newSchema()
    .query(newObject()
        .name("Query")
        .field(newFieldDefinition()
            .name("hello")
            .type(GraphQLString)
            .dataFetcher(environment -> "world"))
        .build())
    .build();

Both examples demonstrate creating a simple GraphQL schema with a "hello" query that returns "world". The graphql-go version uses a more compact syntax, while graphql-java employs a builder pattern, which can be more verbose but offers greater flexibility for complex schemas.

Convert Figma logo designs to code with AI

Visual Copilot

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

Try Visual Copilot

README

GraphQL Java

Discuss and ask questions in our Discussions: https://github.com/graphql-java/graphql-java/discussions

This is a GraphQL Java implementation.

Latest build in Maven central: https://repo1.maven.org/maven2/com/graphql-java/graphql-java/

Build Latest Release Latest Snapshot MIT licensed

Documentation

The GraphQL Java book, from the maintainers: GraphQL with Java and Spring

See our tutorial for beginners: Getting started with GraphQL Java and Spring Boot

For further details, please see the documentation: https://www.graphql-java.com/documentation/getting-started

If you're looking to learn more, we (the maintainers) have written a book! GraphQL with Java and Spring includes everything you need to know to build a production ready GraphQL service. The book is available on Leanpub and Amazon.

Please take a look at our list of releases if you want to learn more about new releases and the changelog.

Code of Conduct

Please note that this project is released with a Contributor Code of Conduct. By contributing to this project (commenting or opening PR/Issues etc) you are agreeing to follow this conduct, so please take the time to read it.

License

Copyright (c) 2015, Andreas Marek and Contributors

Supported by

YourKit

YourKit supports this project by providing the YourKit Java Profiler.