How To Use GraphQL In Plain JavaScript

GraphQL is a powerful query language and server-side runtime for APIs, developed by Facebook in 2012 and released as an open-source project in 2015, GraphQL offers a more flexible and efficient alternative to REST APIs, unlike RESTful APIs, which often require multiple round trips to fetch
related resources.
GraphQL is designed to make APIs fast, flexible, and developer-friendly. As an alternative to REST, GraphQL has been an excellent tool for developers because it renders just what you need, nothing more, nothing less, in a single API call. It allows clients to request exactly the data they need, potentially reducing over-fetching and under-fetching issues that are common in traditional REST APIs. GraphQL enables you to fetch all related data in a single request. This makes it particularly
efficient for complex applications where fetching related resources through multiple REST endpoints would be cumbersome. In this guide, we will explore how to use GraphQL in plain JavaScript, without relying on any JavaScript frameworks or libraries like Apollo Client or Relay. This will give you a deeper understanding of how GraphQL works and how to communicate with GraphQL endpoints using just JavaScript.

Understanding GraphQL

GraphQL is a query language and runtime for APIs that allows clients to request exactly the data they need. GraphQL enables you to fetch all related data in a single request. This makes it particularly efficient for complex applications where fetching related resources through multiple REST endpoints would be cumbersome.
With REST, the server defines the structure of the response, and the client has to adapt. This can lead to problems like receiving more data than necessary (over-fetching) or needing to make additional requests to get related data (under-fetching). GraphQL resolves these issues by giving the client full control over the shape and size of the data it requests. Before we dive into using GraphQL with plain JavaScript, it's essential to understand the basic concepts of GraphQL. Here are some of the key terms and concepts:

    Query: A query in GraphQL is a request for data. It specifies what data you want, and the server
    responds with the exact data structure requested, nothing more, nothing less.

      Mutation: While queries are used to fetch data, mutations are used to modify or create new data.
      They are similar to POST, PUT, PATCH, and DELETE operations in REST.

        Schema: The schema defines the structure of the GraphQL API. It specifies the types of data that
        can be queried and mutated and what operations are allowed.

          Resolver: Resolvers are functions that handle the fetching of data for a given query or mutation.
          They link the fields in the schema to the actual data sources (e.g., databases).

            Key Benefits of GraphQL

            1. Flexible and precise data fetching: You can request exactly what you need and nothing
              more, reducing unnecessary data transfer.
            2. Single request for related data: Fetch related data in one request, even if the data comes
              from different resources.
            3. Strongly typed schema: GraphQL APIs are strongly typed, meaning the structure of the
              data is defined in a schema, allowing you to validate queries before executing them.
            4. Versionless API: With GraphQL, you don’t need to version your API as you would with
              REST. You can add new fields or types without breaking existing queries.
            5. Introspective: GraphQL provides introspection, which allows clients to query the API
              schema itself and automatically generate documentation or build powerful tools.
            Flexible and precise data fetching: You can request exactly what you need and nothing
            more, reducing unnecessary data transfer.

            Single request for related data: Fetch related data in one request, even if the data comes
            from different resources.

            Strongly typed schema: GraphQL APIs are strongly typed, meaning the structure of the
            data is defined in a schema, allowing you to validate queries before executing them.

            Versionless API: With GraphQL, you don’t need to version your API as you would with
            REST. You can add new fields or types without breaking existing queries.

            Introspective: GraphQL provides introspection, which allows clients to query the API
            schema itself and automatically generate documentation or build powerful tools.

            Requirements for Requests

            When using vanilla JavaScript, the process used in requesting GraphQL and REST isn’t so different. When using the Fetch method, they have similar contents with a slight addition to GraphQL requests. The following are the requirements for a GraphQL request with Vanilla JavaScript:
            <details>
            <summary>Request Body</summary><p> This is where we’ll send our JSON body to the GraphQL server. The JSON body can contain the following:<br> <b>Operation type</b>: This could be a query or mutation. This describes what type of<br>operation you’re trying to carry out on the GraphQL API.<br> <b>Operation name</b>: This is a meaningful and explicit name for your operation. The<br>Operation name isn’t always required, but its use is encouraged because it is very helpful<br>when debugging.<br><b> Query</b>: This string contains the GraphQL syntax. It is usually enclosed in backticks (`).<br><b> Variables</b>: This is an optional object that lets you pass data separately from the query<br>itself. Due to the difficulty of constructing a string with dynamic values, you can use<br>variable objects for anything dynamic while making the query part.<br><b> Variable definitions</b>: They work just like the argument definitions for a function in a<br>typed language. All the variables required for the query are specified in the variable<br>definition prefixed by $, followed by their type. Variable definitions can be optional or<br>required.</p></details>

            Setting Up GraphQL Query in Plain JavaScript

            To interact with a GraphQL API, you will need to send HTTP requests containing GraphQL queries. I have a working GraphQL server, let’s focus on how to make GraphQL queries from a front-end application using plain JavaScript. The simplest way to do this is using the fetch API in JavaScript. Let’s start by writing a simple GraphQL query and sending it to a GraphQL endpoint.

            GraphQL Queries

            A GraphQL query is a string that represents the structure of the data you want to retrieve from the server. A GraphQL Query returns a response with only what was asked. This approach gives the client more power. Within the GraphQL query, we specify all the data we need from the GraphQL API. In order to send a GraphQL query to the server, we’ll need to make an HTTP request to the GraphQL endpoint. We can do this using the native fetch() API, which is supported by modern browsers. This sends a POST request to the /graphql endpoint, with the query in the body. The server will then process the query and return the requested data in the response. This is the only endpoint to the GraphQL server.

            HTTP Method

            In the context of GraphQL, the HTTP method used for the request is usually POST, regardless of whether you’re making a query or a mutation. This is because GraphQL is designed to send a single POST request to a dedicated endpoint, however, GET can also be used for queries in certain cases.

            Headers

            If any, relevant authorization headers are added to the request. It is also a good<br>idea to include a Content-Type header to specify that you’re sending JSON.<

            GraphQL Variables

            While the previous example shows how to query data without variables, GraphQL also supports variables. This allows you to pass dynamic values into your queries, making them more flexible and reusable. In this query, $id is a variable that can be passed dynamically at runtime. The exclamation mark (!) indicates that the variable is required.

            GraphQL Mutations

            In addition to querying data, you can also modify data using mutations. Mutations in GraphQL work in a similar way to queries, but instead of fetching data, they perform operations like creating, updating, or deleting data. A mutation in GraphQL is used to perform any action that alters the data on the server. It is analogous to the POST, PUT, PATCH, and DELETE HTTP methods in RESTful APIs. Mutations are defined similarly to queries in GraphQL but typically have a side effect, such
            as updating the database or creating a new resource.

            CONCLUSION

            GraphQL is a versatile and efficient way to work with APIs, and using it with plain JavaScript is straightforward. With this foundation, you can start building more complex GraphQL-powered applications in JavaScript, including real-time updates, authentication, and more. GraphQL's flexibility and power make it an ideal choice for modern APIs, and it can be integrated into almost any front-end or back-end stack.