ruby-on-railsgraphql

Calling a third party graphql api


I have been trying to understand GraphQl and how it is used by reading articles. I've seen how to create an api via graphQl, however i havent seen an article which demonstrates how a third party would call a graphQl api.

In my experience i've mainly called RESTful api's with httparty gem (I work with ruby on rails), which has the following format: HTTParty.post(url, headers, body).

However how would someone calling a graphQL api make this request? Would they need to install graphql into their application in order to make the request?(ideally everything should be in the api documentation?) or have I misunderstood how graphql works?


Solution

  • You're on the right track. In a GraphQL API the clients (third party applications) can make requests by sending a GraphQL query to the server that will return a response in JSON

    To make a GraphQL request, the client typically sends a POST request to the GraphQL API endpoint with the JSON payload that contains the GraphQL query. The request can also include variables, which can be used to pass dynamic data to the query. Example:

        POST /graphql HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer <token>
    
        {
          "query": "query ($id: ID!) { user(id: $id) { name } }",
          "variables": {
            "id": "123"
          }
        }
    

    In this example, the asking GraphQL to return the name of the user with the ID of 123. The query field contains the GraphQL query and the variables field contains the variable id which is used to fetch the user with the given id

    The client does not need to install GraphQL into their application. The client can use any HTTP client library that supports sending POST Requests with JSON payloads like httparty in Ruby. The client doesn't need to know anything about the GraphQL schema or types because that info can be found in the API documentation.

    A note on GET vs POST requests with GraphQL; it's generally recommended to use POST requests for more complex queries that require variables or mutations. GET requests are best suited for simple queries that don't require complex input. The other caveat on GET requests is some GraphQL APIs may not support GET requests so would want to make sure to check the documentation to see what request methods are supported