Search code examples
graphqlapolloapollo-server

How do I generate the schema.graphql file when using Apollo Server?


When using Apollo Server to write a GraphQL server, how can I run a command on the server to generate the schema.graphql file for the client to consume? Note: I'm not using the Apollo Client, I'm using Relay.

I know I can run the GraphQL playground and download it from there, but I want a command line that I can automate.

I'm searching for something similar to rake graphql:schema:dump when using GraphQL Ruby which you can run on the server to generate the schema.graphql.


Solution

  • You can use Apollo CLI for that. First install it:

    npm install -g apollo
    

    Then run this command as shown in the docs:

    apollo client:download-schema --endpoint=URL_OF_YOUR_ENDPOINT schema.graphql
    

    The command will generate either the introspection result or the schema in SDL depending on the extension used for the output file.

    Your ApolloServer instance does not expose the schema it creates, but you can also run an introspection query directly against the instance:

    const { getIntrospectionQuery, buildClientSchema, printSchema } = require('graphql')
    const { ApolloServer } = require('apollo-server')
    
    const apollo = new ApolloServer({ ... })
    const { data } = await apollo.executeOperation({ query: getIntrospectionQuery() })
    const schema = buildClientSchema(data)
    console.log(printSchema(schema))
    

    If you're passing an existing GraphQLSchema instance to Apollo Server, you can also just call printSchema on it directly.