SDL-first, directive-driven GraphQL for Ruby on Rails.
Lighthouse lets you build a GraphQL API for your Rails app primarily through your
schema (SDL) and a set of server-side directives — @all, @find,
@paginate, @hasMany, @belongsTo, @whereConditions, @orderBy, @field,
@auth and more — instead of hand-writing a resolver for every field. It is a
Ruby adaptation of the PHP Lighthouse library,
built on top of graphql-ruby, with first-class
Apollo Federation support so a Rails service can act as a subgraph.
type Query {
users: [User!]! @all
user(id: ID! @eq): User @find
}
type User {
id: ID!
customAttributes: String # resolves to user.custom_attributes automatically
posts: [Post!]! @hasMany # batched via a Dataloader
}That's the whole resolver layer for those fields. No Ruby classes required.
Authorize the type, not only the field.
@guardand@can*protect the field they're on, and a client reaches the same records through any relation (comment.post). Define graphql-ruby'sscope_items/authorized?onTypes::PostTypeand everyPostLighthouse loads goes through them: root fields, pages and their totals, batched relations, counts and federated entities. See records reached through a relation.
Writing a resolver class for every field is repetitive. The vast majority of
GraphQL fields do one of a handful of things: list a model, find one by id,
paginate, walk a relationship, or read an attribute. Lighthouse — like its PHP
inspiration — captures those patterns as directives you attach in the schema,
and falls back to a sensible default reader for plain fields. You write Ruby only
for the genuinely custom parts (@field(resolver: "...")), and your schema stays
the single source of truth. Motivation explains the idea in depth.
The same directives reach the rest of an API, too:
- real-time updates:
Subscriptionfields on graphql-ruby's subscriptions, triggered by a mutation's@broadcast, over WebSocket (Action Cable) and Server-Sent Events at once (choosing a transport); - soft deletes (
@softDeletes,@restore,@forceDelete) and feature flags (@feature); - request lifecycle events;
- a controller concern that serves the schema in a few lines.
- Lighthouse (PHP) — the directive vocabulary, the SDL-first philosophy, and the arg-resolver / nested-mutation ideas.
- graphql-ruby — the execution engine,
Dataloader, and the connection/pagination types Lighthouse builds on. - Apollo Federation — so a Rails app can be one subgraph in a larger supergraph.
Add the gem to your Gemfile:
gem 'lighthouse-graphql'It depends on graphql ~> 2.5 and activesupport. Federation needs nothing more.
On graphql 2.5, keep the json gem below 3: graphql 2.5 calls JSON.generate
with an option json 3 removed (graphql 2.6 no longer does).
Then let the generators set the app up:
bin/rails generate graphql:install # graphql-ruby's, with the options you choose (optional)
bin/rails generate lighthouse:installlighthouse:install builds on graphql-ruby's own install, and runs graphql:install
with its defaults when the app has none. It adapts what graphql-ruby wrote: the
schema class becomes Lighthouse's, built from the SDL on graphql-ruby's root types
and base classes, and the rest of its body stays; the base object, interface, union
and scalar include Lighthouse::GraphQL::Type; the controller serves the schema
through Lighthouse::GraphQL::Controller. It adds the initializer, a starter schema
in graphql/schema.graphql and a graphql.config.yml for your IDE. Run
bin/rails generate lighthouse:install --help for its options (--schema,
--schema-path, --subscriptions, --skip-controller, --skip-ide), and see
docs/generators.md for every generator, graphql-ruby's included.
As in PHP Lighthouse, the schema is read from one entrypoint,
graphql/schema.graphql, which #imports the other files
(#import user.graphql, #import blog/*.graphql). A type is defined once, and the
other files add to it with extend type Query. See
docs/schema-organisation.md.
Lighthouse's directives and the types it generates (Paginator/Connection types,
@whereConditions and @orderBy inputs, the _ placeholder, …) are defined in
Ruby, so your IDE can't see them in your .graphql files. Lighthouse writes them
to schema-directives.graphql and programmatic-types.graphql in the app root:
in development on every boot and reload, or with:
bin/rails lighthouse:ide_helperThe generated graphql.config.yml already points the GraphQL plugins for
JetBrains IDEs and VS Code at them. See docs/getting-started.md.
Prefer to wire it by hand? These are the steps the generator performs.
-
Put your SDL in
app/graphqlor any folder (default:RAILS_ROOT/graphql), split across as many.graphqlfiles as you like:# graphql/users.graphql type Query { users: [User!]! @paginate user(id: ID! @eq): User @find } type User { id: ID! name: String email: String posts: [Post!]! @hasMany }
-
Build the schema: graphql-ruby's schema class (
app/graphql/app_schema.rb), inheriting from the schema Lighthouse builds instead ofGraphQL::Schema:class AppSchema < Lighthouse::GraphQL::RbLightHouse.get_schema( options: { base_types: { # the classes graphql-ruby's install writes query_type: Types::QueryType, mutation_type: Types::MutationType, node: Types::NodeType, resolver: Resolvers::BaseResolver, mutation: Mutations::BaseMutation, object: Types::BaseObject # interface: Types::BaseInterface, union:, scalar:, enum:, input_object: ... } } ) use GraphQL::Dataloader # Lighthouse batches relationships through it max_depth(15) end
-
Execute it from your controller exactly like any graphql-ruby schema:
AppSchema.execute(params[:query], variables: params[:variables], context: { current_user: current_user })
See docs/getting-started.md for the full setup, including base types and configuration.
examples/graphql/ is a small blog API built with Lighthouse on Rails 8.1. It shows
the schema, the generated Resolvers::/Mutations::/Subscriptions::/Builders::/Validators:: classes
under graphql-ruby's base classes,
Pundit policies and the opt-in performance features working together, and its specs
are the library's end-to-end suite. See examples/graphql/README.md.
examples/graphql-federations/ is the same blog split into two Apollo
Federation subgraphs, accounts and blog (two Rails apps), behind Apollo Router: entities across them,
an entity interface and @interfaceObject, @requires/@provides/@override/@context, subscriptions
through the router's HTTP callbacks, uploads, persisted queries and @defer, all driven through the router
by its suite. See examples/graphql-federations/README.md.
Read it at manuel-antunes.github.io/lighthouse-graphql,
or as Markdown in docs/:
| Guide | What it covers |
|---|---|
| Motivation | Where Lighthouse comes from, why the schema comes first, and why directives fit Active Record |
| Getting started | Install, base types, building & serving the schema |
| Directives reference | Every built-in directive, grouped by purpose |
| Relationships | @hasMany, @belongsTo, @belongsToMany, @hasOne, the @morph* variants, batching and type: pagination |
| Filtering & ordering | @eq/@where/@in/@like, @whereConditions, @orderBy |
| Resolvers, mutations & builders | Resolvers:: / Mutations:: classes and their base classes (graphql-ruby's contract), builders, generators |
| Mutations | @create, @update, @upsert, @delete (and *Many), nested mutations on every kind of association, @spread, @inject |
| Validation | Model validations, @validator with Dry::Validation contracts |
| Authentication & authorization | @guard, @canFind / @canModel / @canQuery / @canResolved / @canRoot (Pundit by default) |
| Performance at scale | Opt-in schema cache, SDL reloading in development, persisted queries (APQ) and trusted-document allowlists |
| Events | Request, schema-build and execution events, @event, the controller concern |
| Subscriptions | Subscription fields, @subscription, @broadcast, filtering and queued broadcasts, over WebSocket or Server-Sent Events |
| Caching | @cache, @cacheKey, @clearCache (Rails.cache), @cacheControl (HTTP) |
| Apollo Federation | Subgraphs: @key entities, entity interfaces, the subgraph SDL, subscriptions through Apollo Router |
| Custom directives | The contracts, the registry, writing your own directive |
| Configuration | Lighthouse.configure, namespaces, error handling |
| Best practices | Conventions worth adopting |
Lighthouse parses your SDL, runs a manipulation phase (directives that need to
reshape the schema — e.g. @paginate injecting a Paginator type, @whereConditions
generating input types), builds an executable schema with
GraphQL::Schema.from_definition, then runs a resolution phase that attaches
behavior to fields (directives that resolve data, wrap resolvers, or compose query
constraints). Every directive is a small class registered with a
Lighthouse::DirectiveRegistry; adding one is "write a class and register it." A
single Support::Naming rule maps GraphQL camelCase to Rails snake_case, so
attribute reads "just work" with @rename as the explicit override.
MIT. See LICENSE.txt.