GraphQL, a modern query language for APIs, paired with Ruby on Rails, offers a powerful combination for streamlined API development. In this quick guide, we’ll walk through the essential steps to set up a GraphQL API in a Ruby on Rails application, providing you with a solid foundation for efficient and flexible web development.
Étape 1 : Créer un nouveau projet Rails
frapper
rails new graphql_examplecd graphql_example
Étape 2 : Ajouter les gems nécessaires à votre Gemfile
Ajoutez les pierres précieuses suivantes à votre Fichier de gemmes:
rubis
gem 'graphql'gem 'graphiql-rails', group : :development
Courir installation groupée pour installer les nouvelles pierres précieuses.
Étape 3 : Créer un schéma GraphQL
Créer un fichier nommé app/graphql/types/query_type.rb:
rubis
# app/graphql/types/query_type.rbTypes::QueryType = GraphQL::ObjectType.define do
nom 'Query' (requête)'
description 'Le type de requête racine'
champ :hello do
type types.String
description 'Un champ d'exemple'
resolve ->(_obj, _args, _ctx) { 'Hello, GraphQL!' }
fin
fin
Étape 4 : Créer un contrôleur GraphQL
Générer un contrôleur pour traiter les requêtes GraphQL :
frapper
rails generate controller graphql execute
Remplacer le contenu de app/controllers/graphql_controller.rb avec les éléments suivants :
rubis
# app/controllers/graphql_controller.rbclasse GraphqlController < ApplicationController
def execute
variables = ensure_hash(params[:variables])
query = params[:query]
nom_opération = params[:nom_opération]
contexte = {
# Ajoutez ici toutes les valeurs de contexte nécessaires, telles que current_user ou session
}
result = Schema.execute(query, variables : variables, context : context, operation_name : operation_name)
render json : result
fin
privé
def ensure_hash(variables)
variables de cas
quand Chaîne
JSON.parse(variables) || {}
lorsque Hash
variables
quand nil
{}
autre
raise ArgumentError, "Variables non valides : #{variables}"
fin
fin
fin
Étape 5 : Créer le schéma GraphQL
Créer un fichier nommé app/graphql/schema.rb:
rubis
# app/graphql/schema.rbSchema = GraphQL::Schema.define do
query(Types::QueryType)
# Add mutation types if needed
fin
Step 6: Configure routes
Update your config/routes.rb to include the GraphQL endpoint:
rubis
# config/routes.rbRails.application.routes.draw faire
post '/graphql', to: 'graphql#execute'
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: '/graphiql', graphql_path: '/graphql'
fin
fin
Step 7: Run your Rails server
frapper
rails s
Visit http://localhost:3000/graphiql in your browser to use GraphiQL, an in-browser IDE for exploring GraphQL.
In the GraphiQL interface, you can enter a query like:
graphql
{hello
}
And you should receive a response:
json
{"data": {
"hello": "Hello, GraphQL!"
}
}
This is a simple example, but you can expand your GraphQL schema with more types and mutations to suit your application’s needs.
Conclusion
By following this quick setup guide, you’ll be well-equipped to integrate GraphQL into your Ruby on Rails projects seamlessly. Harness the power of GraphQL to create APIs that cater to your application’s specific needs while providing an excellent developer and user experience. Get ready to elevate your API development game with the simplicity and flexibility of GraphQL in Ruby on Rails. Elevate your company’s digital presence with top-tier Ruby on Rails developers de RailsCarma. Our seasoned professionals bring a wealth of experience and innovation to the table, ensuring your projects are not only executed seamlessly but exceed industry standards.