Writing a GraphQL Client

Mirko Nasato
A free video tutorial from Mirko Nasato
Software Developer and Mentor
4.7 instructor rating • 2 courses • 19,711 students

Learn more from the full course

GraphQL by Example

Learn GraphQL by writing full-stack JavaScript applications with Node.js, Express, Apollo Server, React, Apollo Client.

05:20:52 of on-demand video • Updated March 2021

  • Build a GraphQL server based on NodeJS, Express and Apollo Server
  • Invoke GraphQL APIs from JavaScript client applications using regular HTTP requests or Apollo Client
  • Handle Authentication/Authorization, Caching, and more
English So that's what a GraphQL request looks like when sent over HTTP. The client is POSTing some JSON, and the server sends some JSON back, nothing too fancy. Now that we know this, writing our own client should be pretty simple. Let's go and create a new project. I am where I created my "hello-world" folder that contains our server project. I'll now add a "client" folder as well and open it in Visual Studio Code. So, as our first GraphQL client we'll write a basic web page with some vanilla JavaScript code that sends a request to our GraphQL server, without even using any frameworks. Let's start by creating a new file called "index.html". And here I'll use the "html:5" snippet to generate the basic HTML boilerplate. So this is just an empty web page. Let's set the title to "GraphQL Client", then let's add an "h1" heading also saying "GraphQL Client" for now. Now, let me open this file in the browser and this is our basic page. Nothing exciting so far. I'll keep the browser and the editor side by side, so we can see both. Now, let's say that instead of this text we want to display the "greeting" message returned from our GraphQL Server. Let's change this text to "Loading..." initially, then we'll replace the text once we get the response from the server. Next we'll need some JavaScript code, so let's add a "script" tag and set the "src" to "app.js". Then let's go and create that "app.js" file. And here we'll write the code to fetch the greeting from the server. So let's write a function, called "fetchGreeting". There are a couple of ways to make HTTP requests from the browser. In this example I'll use the "fetch" API, which is a web standard so we don't need any additional libraries. The URL we want to call is the same one we used in the Playground Let's create a variable at the top called "GRAPHQL_URL" and paste the URL here: "localhost" on port 9000. So we want to "fetch" that URL, then we need to pass some options. The "method" must be "POST". Next, we want to set some "headers". in fact we just need one, that is the "content-type" and this will be "application/json". Finally we need to send a "body" and here we can use "JSON.stringify" to convert a JavaScript object to JSON automatically. In the body we need a "query" property. And the value of this string will be exactly the same query string we used in the Playground, so let's copy it from there. And then paste our query string into our code here. That's it for the request. Now let's process the response. I'm going to declare this function as "async" so we can use the "await" keyword inside this function. Now let's get the "response" by "awaiting" the result of "fetch", since making an HTTP request is asynchronous. Next, we want to parse the response as JSON and this response object has a "json" method to do exactly that. So the result will be the "responseBody" and we need to "await" the result, because with the Fetch API parsing the JSON also returns a Promise. At this point let's just log the "responseBody" to the console. And for now let's just call our "fetchGreeting" function right here, so it will run as soon as the page is loaded. Let's save this file and see what happens. I'll open the DevTools so we can see the console messages. Now let's reload the page and that's the server response in the console. As usual we get our "greeting" message wrapped in a "data" property. Since we know the format of the response object we can extract the "data" property from the "responseBody" using the object destructuring syntax. and, instead of logging the response let's return the "data". The final thing we want to do is replace the text in our page with the greeting returned by the server. So here we can call "then", because "fetchGreeting" is an async function and therefore returns a Promise. And here we'll receive the "data", that we can also destructure extracting the "greeting" property, which is all we need. Once we get the greeting we want to change the text displayed on the page. Let's have a look at our HTML again. We want to set the content of the "h1" tag. So in our JavaScript code we can use "document.querySelector" to find the "h1" tag by name. (We know there's only one h1 tag in our page.) Let's assign the element to a variable, say "title". Finally we can set the "title.textContent" to be the value of the "greeting" we got from the server. Right, let's see if this works. If we reload the page… there's our "Hello GraphQL world" message! So, this is a simple example of how to make a GraphQL request over HTTP. There are also GraphQL client libraries available for many languages that make things a bit nicer. But I wanted you to understand that at the end of the day any GraphQL client just uses HTTP under the hood, there's nothing magic going on. And since it is just HTTP this also means that we can call our GraphQL server from pretty much any language or platform, as long as it provides a way to make HTTP requests.