Easily generate beautiful documentation from your GraphQL schema.
Easily generate beautiful documentation from your GraphQL schema.
Ruby library and CLI for easily generating beautiful documentation from your GraphQL schema.
Key links:
Add the gem to your project with this command:
bundle add graphql-docsOr install it yourself as:
gem install graphql-docsGraphQLDocs provides two ways to serve your documentation:
GraphQLDocs can be used as a Ruby library to build the documentation website. Using it as a Ruby library allows for more control and using every supported option. Here's an example:
# pass in a filename
GraphQLDocs.build(filename: filename)
# or pass in a string
GraphQLDocs.build(schema: contents)
# or a schema class
schema = GraphQL::Schema.define do
query query_type
end
GraphQLDocs.build(schema: schema)GraphQLDocs also has a simplified CLI (graphql-docs) that gets installed with the gem:
graphql-docs schema.graphqlThat will generate the output in the output dir.
See all of the supported CLI options with:
graphql-docs -hGraphQLDocs includes a Rake task for integration with Rails applications and other Ruby projects that use Rake. This allows you to generate documentation as part of your build process or hook it into other Rake tasks.
Using task arguments (recommended):
rake graphql-docs:generate[schema.graphql]
rake graphql-docs:generate[schema.graphql,./docs]
rake graphql-docs:generate[schema.graphql,./docs,/api-docs,true]Or using environment variables:
GRAPHQL_SCHEMA_FILE=schema.graphql rake graphql-docs:generateArguments are passed in order: [schema_file, output_dir, base_url, delete_output]
schema_file - Path to GraphQL schema file (required)output_dir - Output directory (default: ./output/)base_url - Base URL for assets and links (default: '')delete_output - Delete output directory before generating (true/false, default: false)GRAPHQL_SCHEMA_FILE - Path to GraphQL schema file (required)GRAPHQL_OUTPUT_DIR - Output directory (default: ./output/)GRAPHQL_BASE_URL - Base URL for assets and links (default: '')GRAPHQL_DELETE_OUTPUT - Delete output directory before generating (true/false)Note: Task arguments take precedence over environment variables.
In Rails, you can automatically generate documentation before compiling assets:
# Rakefile or lib/tasks/docs.rake
Rake::Task["assets:precompile"].enhance(["graphql-docs:generate"])Then configure using environment variables:
# config/application.rb or .env
ENV["GRAPHQL_SCHEMA_FILE"] = Rails.root.join("app/graphql/schema.graphql").to_sOr invoke with arguments in your custom task:
# lib/tasks/custom_docs.rake
namespace :docs do
desc "Generate API documentation"
task :generate do
Rake::Task["graphql-docs:generate"].invoke(
"app/graphql/schema.graphql", # schema_file
"public/api-docs", # output_dir
"/api-docs", # base_url
"true" # delete_output
)
end
end
# Hook into asset compilation
Rake::Task["assets:precompile"].enhance(["docs:generate"])For more flexibility and control, you can serve documentation dynamically using the Rack application. This is useful for:
Requirements: The Rack application feature requires the rack gem (version 2.x or 3.x). Add it to your Gemfile:
gem 'rack', '~> 3.0' # or '~> 2.0' for Rack 2.xThe gem is compatible with both Rack 2.x and 3.x, so you can use whichever version your application requires.
Create a config.ru file:
require 'graphql-docs'
schema = File.read('schema.graphql')
app = GraphQLDocs::App.new(
schema: schema,
options: {
base_url: '',
use_default_styles: true,
cache: true # Enable page caching
}
)
run appThen run with:
rackup config.ruVisit http://localhost:9292 to view your docs.
# config/routes.rb
require 'graphql-docs'
Rails.application.routes.draw do
mount GraphQLDocs::App.new(schema: MyGraphQLSchema) => '/docs'
endrequire 'sinatra'
require 'graphql-docs'
schema = File.read('schema.graphql')
docs_app = GraphQLDocs::App.new(schema: schema)
map '/docs' do
run docs_app
end
map '/' do
run Sinatra::Application
endcache: false)app = GraphQLDocs::App.new(schema: schema)
# Later, reload with new schema
new_schema = File.read('updated_schema.graphql')
app.reload_schema!(new_schema)| Feature | SSG | Rack App |
|---|---|---|
| Setup complexity | Low | Medium |
| First page load | Instant | Fast (with caching) |
| Schema updates | Manual rebuild | Automatic/reload |
| Hosting | Any static host | Requires Ruby server |
| Memory usage | Minimal | Higher (cached pages) |
| Authentication | Separate layer | Built-in middleware |
| Best for | Public docs, open source | Internal tools, dynamic schemas |
There are several phases going on the single GraphQLDocs.build call:
filename) through GraphQL::Client (or simply read if you passed a string through schema).GraphQL::Parser manipulates the IDL into a slightly saner format.GraphQL::Generator takes that saner format and begins the process of applying items to the HTML templates.GraphQL::Renderer technically runs as part of the generation phase. It passes the contents of each page and converts it into HTML.If you wanted to, you could break these calls up individually. For example:
options = {}
options[:filename] = "#{File.dirname(__FILE__)}/../data/graphql/schema.idl"
options[:renderer] = MySuperCoolRenderer
options = GraphQLDocs::Configuration::GRAPHQLDOCS_DEFAULTS.merge(options)
response = File.read(options[:filename])
parser = GraphQLDocs::Parser.new(response, options)
parsed_schema = parser.parse
generator = GraphQLDocs::Generator.new(parsed_schema, options)
generator.generateBy default, the HTML generation process uses ERB to layout the content. There are a bunch of default options provided for you, but feel free to override any of these. The Configuration section below has more information on what you can change.
It uses Commonmarker (v2.x) to perform the Markdown rendering by default, with GitHub Flavored Markdown extensions enabled including automatic header anchors. Emoji shortcodes (like :smile:) are automatically converted to emoji characters using gemoji. You can override this by providing a custom rendering class. You must implement two methods:
initialize - Takes two arguments, the parsed schema and the configuration options.render Takes the contents of a template page. It also takes two optional kwargs, the GraphQL type and its name. For example:class CustomRenderer
def initialize(parsed_schema, options)
@parsed_schema = parsed_schema
@options = options
end
def render(contents, type: nil, name: nil)
contents.sub(/Repository/i, 'Meow Woof!')
opts[:content] = contents
@graphql_default_layout.result(OpenStruct.new(opts).instance_eval { binding })
end
end
options[:filename] = 'location/to/sw-api.graphql'
options[:renderer] = CustomRenderer
GraphQLDocs.build(options)If your render method returns nil, the Generator will not attempt to write any HTML file.
The layouts for the individual GraphQL pages are ERB templates, but you can also use ERB templates for your static landing pages.
If you want to add additional variables for your landing pages, you can add define a variables hash within the landing_pages option.
In your ERB layouts, there are several helper methods you can use. The helper methods are:
slugify(str) - This slugifies the given string.include(filename, opts) - This embeds a template from your includes folder, passing along the local options provided.markdownify(string) - This converts a string into HTML via CommonMarker.graphql_operation_types, graphql_mutation_types, graphql_object_types, graphql_interface_types, graphql_enum_types, graphql_union_types, graphql_input_object_types, graphql_scalar_types, graphql_directive_types - Collections of the various GraphQL types.To call these methods within templates, you must use the dot notation, such as ``.
GraphQLDocs includes built-in dark mode support that automatically adapts to the user's system preferences using the prefers-color-scheme media query. When a user has dark mode enabled on their operating system, the documentation will automatically display with a dark theme.
The default styles use CSS custom properties (variables) for all colors, making it easy to customize the color scheme to match your brand. You can override these variables by providing a custom stylesheet.
The available CSS variables are:
Light Mode (default):
…Dark Mode:
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #1a1a1a;
--bg-secondary: #252525;
--bg-tertiary: #2a2a2a;
--bg-code: #333;
--bg-code-block: #1e1e1e;
--text-primary: #e0e0e0;
--text-secondary: #888;
--text-link: #ff6b6b;
--text-code: #d4d4d4;
--border-color: #333;
--border-color-secondary: #444;
--shadow-color: rgba(255, 255, 255, 0.1);
}
}To customize the colors, create a custom CSS file and load it after the default styles. You can override specific variables while keeping the rest of the defaults:
/* custom-theme.css */
:root {
--text-link: #0066cc; /* Change link color to blue */
--bg-tertiary: #f0f0f0; /* Lighter API boxes */
}
@media (prefers-color-scheme: dark) {
:root {
--text-link: #66b3ff; /* Lighter blue for dark mode */
--bg-primary: #0d1117; /* GitHub-like dark background */
--bg-secondary: #161b22;
}
}Then reference it in your custom template by overriding the default template and adding a link to your stylesheet:
/assets/style.css" />
/assets/custom-theme.css" />The following options are available:
| Option | Description | Default
No open issues yet, or sync has not completed.