Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to expose 2 graphql endpoints using spring boot starter app graphql-spring-boot-starter?

Currently we are using

    <dependency>
        <groupId>com.graphql-java-kickstart</groupId>
        <artifactId>graphql-spring-boot-starter</artifactId>
        <version>${graphql-spring-starter.version}</version>
    </dependency>

With this, we are exposing our graphql API using /graphql endpoint. I want to have multiple endpoints like this, /graphql1 and /graphql2 so that I can define different response formats based on the endpoints. what is the best way to do it? Any inputs is highly appreciated.

like image 724
dilip280 Avatar asked Jun 04 '20 18:06

dilip280


People also ask

Can I have multiple GraphQL endpoints?

GraphQL is all about having a single endpoint to query the data, but there are situations where it makes sense to instead have multiple endpoints, where each custom endpoint exposes a customized schema.

Does GraphQL have one endpoint?

GraphQL is typically served over HTTP via a single endpoint which expresses the full set of capabilities of the service. This is in contrast to REST APIs which expose a suite of URLs each of which expose a single resource.

Can you use GraphQL with spring boot?

The Spring Boot GraphQL Starter offers a fantastic way to get a GraphQL server running in a very short time. Using autoconfiguration and an annotation-based programming approach, we need only write the code necessary for our service.


1 Answers

It just boils down to create a GraphQLHttpServlet and configure its context path. Under the cover , it uses auto-configuration GraphQLWebAutoConfiguration to define a GraphQLHttpServlet as a bean, and configure the context path to be /graphql.

That means you can reference how GraphQLWebAutoConfiguration does and create another GraphQLHttpServlet instance that registered to other context path.

The main point is that to register a Servlet in spring boot , you can simply create a ServletRegistrationBean that wraps the HttpServlet which you want to create .See docs for more details.

A simple example is :

@Bean
public ServletRegistrationBean<AbstractGraphQLHttpServlet> fooGraphQLServlet() {
    //Create and configure the GraphQL Schema.
    GraphQLSchema schema = xxxxxxx;

    GraphQLHttpServlet graphQLHttpServlet = GraphQLHttpServlet.with(schema);
    ServletRegistrationBean<AbstractGraphQLHttpServlet> registration = new ServletRegistrationBean<>(
                    graphQLHttpServlet, "/graphql2/*");

    registration.setName("Another GraphQL Endpoint");
    return registration;
} 
like image 143
Ken Chan Avatar answered Nov 22 '22 07:11

Ken Chan