GraphQL Client starting with Ruby

What is this

What is GraphQL?

It is difficult to express what GraphQL is in one word, but I personally recognize it as "a kind of protocol that expresses API". Often compared to the REST API. With REST API

curl http://example.com/users/123/posts/

In GraphQL, you can hit it like this

curl http://example.com/graphql -X POST --data '
  {
    user("123") {
      posts {
        title
      }
    }
  }
'

Hit like. The REST API makes requests to various URLs such as / users / / users / 123 / / users / 123 / posts / to get the desired information, but GraphQL has one end. By throwing various queries to the points, you can get all the necessary information (except unnecessary information) with one request.

Learn how to use GraphQL API

I wish I could use the GraphQL API in a hurry, so I only read the Queries and Mutations and Schemas and Types of the official GraphQL guide (https://graphql.org/learn/). I recommend it because you can get an overview just by reading two slightly longer pages.

However, there is one caveat. ** Don't ponder the meaning of the APIs that appear as examples. ** For example, the following query appears at the beginning.

{
  hero {
    name
  }
}

In response, the sample API returns this response:

{
  "data": {
    "hero": {
      "name": "R2-D2"
    }
  }
}

When I look at this example, I'm wondering, "Why do you return R2-D2 even though you didn't specify hero_id?" "If you don't specify hero_id, why should you return all heroes?" As a result, it hindered the overall understanding. In reality, this API is just a sample, so you should ignore its practicality and assume that it is something like that. There is simply a "Query called hero that takes one Episode as an optional argument and returns one Character".

Set up a GraphQL server for learning

Apollographql / starwars-server is a reproduction of the mysterious Star Wars API that appears in the official GraphQL guide above. After this, I will use it to hit from Ruby, so let's start it quickly. If you can access http: // localhost: 8080 / graphql from your browser, the startup is successful.

There is graphql / swapi-graphql with a similar name, but it is different because it is a GraphQL wrapper for the more authentic Star Wars API. be careful.

Try using GraphQL client in Ruby

There is github / graphql-client as a GraphQL Client made by Ruby. I was very relieved that github is the owner, so I will use this for the time being.

It is also written in the README, but use it as follows.

require "graphql/client"
require "graphql/client/http"

module SWAPI
  #http adapter set
  HTTP = GraphQL::Client::HTTP.new("http://localhost:8080/graphql")

  #Get GraphQL Schema information from the API server using the above
  Schema = GraphQL::Client.load_schema(HTTP)

  #Create a client using the above
  Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
end

HeroQuery = SWAPI::Client.parse <<~'GRAPHQL'
 {
  hero {
    name
  }
}
GRAPHQL

result = SWAPI::Client.query(HeroQuery)
pp result.to_h

In the above, Schema information is obtained from the server, but it seems that there is also a way to save it locally in advance and load it as follows.


module SWAPI
  #Set http adapter (same as above)
  HTTP = GraphQL::Client::HTTP.new("http://localhost:8080/graphql")

  #Get GraphQL Schema information from a local file
  Schema = GraphQL::Client.load_schema("path/to/schema.json")

  #Create a client using the above (same as above)
  Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
end

#Get GraphQL Schema information from API server and output to local file
GraphQL::Client.dump_schema(SWAPI::HTTP, "path/to/schema.json")

# ...

important point

If you want to give the query an Operation Name, you need to pass the argument of SWAPI :: Client.query () with the module name.

HeroQuery = SWAPI::Client.parse <<~'GRAPHQL'
 #If you name it NameOfHero ...
 query NameOfHero {
  hero {
    name
  }
}
GRAPHQL

#HeroQuery instead of HeroQuery::You need to pass NameOfHero!
result = SWAPI::Client.query(HeroQuery::NameOfHero)

If you forget this, you will get the error ʻexpected definition to be a GraphQL :: Client :: OperationDefinition but was GraphQL :: Language :: Nodes :: Document (TypeError)`.

Also, because of this, you can't necessarily name names that start with a lowercase letter (you'll get the error client.rb: 241: in'const_set': wrong constant name ... (NameError)).

I feel that all the issues around this ↓ simply overlook this specification.

I was addicted to it because it wasn't specified in the README ... (Contribution chance?)

Recommended Posts

GraphQL Client starting with Ruby
Mutation with GraphQL
Install Ruby 3.0.0 with asdf
Getting Started with Ruby
DataNucleus starting with Gradle
Starting with Swift Swift UI
CarPlay starting with iOS14
11th, Classification with Ruby
Evolve Eevee with Ruby
Play with Jersey OAuth 2 client
Ruby version switching with rbenv
Implement GraphQL with Spring Boot
GraphQL Ruby and actual development
Ruby: Send email with Starttls
Leap year judgment with Ruby
Format Ruby with VS Code
Integer check method with ruby
API creation with Rails + GraphQL
Spring Boot starting with copy
Test GraphQL resolver with rspec
Spring Boot starting with Docker
Ruby Learning # 8 Working With String
Extract a string starting with a capital letter with a regular expression (Ruby)
[Ruby] problem with if statement
Studying with CodeWar (ruby) ⑤ proc
Use Ruby with Google Colab
[Ruby] REPL-driven development with pry
Getting Started with Ruby Modules
[ruby] Method call with argument
Install Ruby on MSYS2 with pacman
Make electronic music with randomness with Ruby
[Java EE] Implement Client with WebSocket
Learning Ruby with AtCoder 6 [Contest 168 Therefore]
Let's use Amazon Textract with Ruby
Programming with ruby (on the way)
Studying with CodeWar (ruby) ④ case ~ when
Run GraphQL Ruby resolver in parallel
[Ruby] Extracting elements with slice method
Implement a gRPC client in Ruby
[Ruby] Handle instance variables with instance methods
Handle DatePicker with Ruby / gtk3 + glade3
Impressions of making BlackJack-cli with Ruby
I tried GraphQL with Spring Boot
Install ruby on Ubuntu 20.04 with rbenv
Make a typing game with ruby
Do your best with gRPC with ruby ​​on the server and PHP on the client