Create your schema by extending the GraphQL::Schema class:
app/graphql/app_schema.rb
module GraphQL class AppSchema < GraphQL::Schema # Schema configuration goes here endend
Each schema is associated with a single namespace. By default, schemas use the :base namespace:
app/graphql/app_schema.rb
module GraphQL class AppSchema < GraphQL::Schema # Set a custom namespace namespace :api # Associate a module with the namespace namespace :api, GraphQL endend
Schemas organize fields into three groups: queries, mutations, and subscriptions.
Query Fields
Mutation Fields
Subscription Fields
app/graphql/app_schema.rb
module GraphQL class AppSchema < GraphQL::Schema query_fields do field :user, 'User', null: false field :users, 'User', array: true end endend
app/graphql/app_schema.rb
module GraphQL class AppSchema < GraphQL::Schema mutation_fields do field :create_user, 'User', null: false field :update_user, 'User', null: false end endend
app/graphql/app_schema.rb
module GraphQL class AppSchema < GraphQL::Schema subscription_fields do field :user_updated, 'User' end endend
For larger applications, consider using alternatives or field lists to organize fields in separate files.
Import fields defined in separate classes or modules:
app/graphql/app_schema.rb
module GraphQL class AppSchema < GraphQL::Schema # Import a single field import_into :query, GraphQL::Queries::Sample # Import all fields from a module import_all GraphQL::Queries # Import recursively import_all GraphQL::Queries, recursive: true endend
For simple schemas or testing, you can define types directly in the schema:
app/graphql/app_schema.rb
module GraphQL class AppSchema < GraphQL::Schema enum 'Episode' do desc 'One of the films in the Star Wars Trilogy' add 'NEW_HOPE', desc: 'Released in 1977.' add 'EMPIRE', desc: 'Released in 1980.' add 'JEDI', desc: 'Released in 1983.' end object 'Human' do desc 'A humanoid creature in the Star Wars universe' field :id, null: false, desc: 'The id of the human' field :name, desc: 'The name of the human' end endend
This approach is recommended only for small schemas or testing. For production applications, organize types in separate files.
Schemas provide shortcuts for interacting with the Type Map:
# Find a type (returns nil if not found)GraphQL::AppSchema.find_type(:string)# Find a type (raises exception if not found)GraphQL::AppSchema.find_type!(:user)# Find a directiveGraphQL::AppSchema.find_directive!('deprecated')# Iterate over all typesGraphQL::AppSchema.types do |type| puts type.gql_nameend