This is a premium alert message you can set from Layout! Get Now!

Debugging GraphQL with Altair

0

GraphQL provides clients with the power and flexibility to selectively request the data they need. Consequently, GraphQL makes it easier to evolve APIs over time.

Altair is a GraphQL API client to explore APIs. It is to GraphQL what Postman is to REST. Altair provides a good alternative to traditional GraphiQL and Playground. It is feature-packed, easy to use, and comes with an inbuilt debugger, making it great for debugging.

In this article, we’ll learn how to debug GraphQL APIs using Altair. So, let’s get started with the prerequisites in the next section.

Prerequisites

The following are required to get the most from this article:

  • Basic knowledge of GraphQL
  • Basic knowledge of working with APIs
  • The latest version of Altair
  • Basic knowledge of using a GraphQL API client like Altair, Playground, or GraphiQL

Debugging with Altair

While Altair is definitely a feature-packed API client, we’re interested in its debugging features for this article.

In programming, debugging is identifying the root cause of an issue and fixing it. During development, we want to be able to debug faster for any errors happening across the different components of an API. Some debugging strategies used include:

  • Brute force techniques such as logging everything, tweaking everything, and trying everything
  • Back-tracing techniques such as stepping back from the error and stepping toward what is working

Let’s see how Altair can streamline our debugging methods.

The Altair developer tool

Altair fosters debugging by allowing us to manipulate inputs and inspect the outputs to better understand the relationship between the two.

As an Electron app, Altair comes with an inbuilt developer tool, which in a nutshell is the developer tool of the Chromium browser. That’s because Electron combines the Chromium rendering engine and the Node.js runtime.

The Chromium browser is essentially unbranded Chrome, and both browsers use the Blink rendering engine and the v8 JavaScript engine. Consequently, they give the same support for CSS, HTML, DOM rendering, JavaScript compatibility, functionality, and performance.

Debugging With Altair

When debugging with Altair, we use both the Altair API client and the Altair developer tool.

The Altair client enables us to manipulate inputs and inspect data. Consequently, it allows us to inspect all the pieces of our request and response — specifically our HTTP response and error messages.

And as a result of this, we can:

  • Update parameters, headers, and queries
  • See HTTP status codes and error messages
  • Parse responses
  • Inspect variables
  • Review query and subscription results
  • Replay calls in the History section

The Altair developer tools provide us with these useful features:

  • The console — a great place for logging statements, inspecting variables, and testing out arbitrary fixes and bugs
  • The Network tab — a great place for inspecting network calls
  • Other features of the Chromium developer tool such as the source panel, performance panel, lighthouse, etc. Note the GraphQL resolvers run on the server, and the server’s code will not appear in the developer tool’s Sources panel

Let’s learn more about the developer tools in the next section.

Debugging GraphQL APIs with Altair

We will need a GraphQL project for this; you can use your own or clone the demo project from here.

The project is a simple Node application that resolves our GraphQL query and returns results from mock data:

export default {
    users: [
        { id: 1, username: 'JohnDoe', email: 'John_doe@gmail.com', password: '12345', role: 'admin' },
        { id: 2, username: 'JaneDoe', email: 'Jane_doe@gmail.com', password: '12345', role: 'user' },
        { id: 3, username: 'JoeDoe', email: 'Joe_doe@gmail.com', password: '12345', role: 'user' }
    ]
};

The user and users fields are protected, and they both require admin-level permission to access. Only the login query is not protected. Our aim in this article is not to learn how the project was built but to learn how to debug GraphQL APIs using this application.

And we will focus on doing that. Let’s set up the project and start debugging.

Project setup

Follow these instructions to set up the project:

  • Create a project directory and cd into the directory:
mkdir <-- project name -->
cd <-- project name -->
  • Clone the project and install dependencies:
// clone project
git clone https://github.com/lawrenceagles/fastify-graphQL-Altair

// install dependencies
npm install
  • Start the server by running:
npm start

With that work, we get:

> fastify-graphql@1.0.0 start /home/eagles/Work/projects/fga
> node  --es-module-specifier-resolution=node ./src/index.js

{"level":30, "time":1646401128942, "pid":8565, "hostname":"your-pc-model","msg":"Server listening at http://127.0.0.1:4500"}

With this all set up, we’ll learn how to work on these debugging issues: the even source error event, 404 not found, 401 unauthorized, 403 forbidden, and 400 bad request.

We will try to replicate and debug these errors as we learn. Let’s start with 401 unauthorized errors.

401 Unauthorized

A 401 Unauthorized error occurs when a user fails authentication, and this can happen for different reasons:

  • Wrong login credentials (username, email, and password)
  • The user fails to provide a token
  • The user provides an invalid token

Let’s replicate and debug this error in our application using the Altair client. Open your Altair client and run the login query using the following code:

query{
    login(username: "JaneDoe", password: "12345xxx") {
        role
        token
    }
}

Make sure to add the following URL to Altair to access our server: http://localhost:4000/graphql. Then, open the Altair developer tool with CTRL + SHIFT + I.

When we run the query, we get:

Running The Query

From the image above, we see that Altair gives us useful error alerts that warn us about the URL. Also, we get the famous ERR_CONNECTION_REFUSED Chrome error.

This is because our URL http://localhost:4000/graphql is not correct. Our server runs on port 4500 and we used port 4000 in the URL construct. This is deliberate to produce this error. Since this article is focused on debugging, we will deliberately throw an error for us to debug.

Update your Altair URL to http://localhost:4500/graphql and try again — be sure to clear your console.

Now we get:

Updating Altair

This immediately tells us there is an issue with our credentials. We can easily fix that by removing the xxx from the password and trying again.

Now we get:

Altair GraphQL Client

The 401 unauthenticated error can also be thrown when we query a protected API without providing a valid token. In our application, the users type is protected. Open a new tab in your Altair client and query this type using the code below:

query {
  users {
    id
    username
    password
    email
    role
  }
}

Now we get:

401 Unauthenticated Error

Since we generated a token in our previous query, let’s use that and see what we get. We will do this as we learn about the 403 forbidden error.

403 Forbidden

Let’s learn how to resolve a 403 Forbidden error. To authenticate a user, our API requires we pass a token via the header using x-user as the key.

In the previous example, we failed to query the users type because we were not authenticated. But since we have generated a token in the login example, copy that token and add it to the users query as seen below:

403 Forbidden error

Click Save and run the query again.

Now we get:

Running Query Again

The 403 error above tells us that we do not have permission to query the users field. In our application, all users have a role — namely admin or user — and this is used to determine what operation a user can perform. The users type requires an admin role or privilege to query it. Therefore, the server understands our query but refuses to authorize it because we do not have the required permission.

Let’s log in with another user credential — JohnDoe, an admin — and generate another token with a user with an admin role.

Open a new tab in your Altair client and run the code below:

query{
    login(username: "JohnDoe", password: "12345") {
        role
        token
    }
}

Now we get:

New Tab In Altair Client

Finally, use this token to run the users query again. And we get:

Running Query

404 Not Found

The 404 Not Found error is thrown when the server fails to find the resource we query for.

To replicate this error, we would query for a single user using the code below:

query{
    user(id: 10) {
        username
        email
        password
        role
    }
}

Now we get:

404 Not Found

And by reviewing the query result from the Altair Results tab, we see that the error message says “Invalid User ID.”

Let’s try the query again with a user that exists. Use the code below:

query{
    user(id: 1) {
        username
        email
        password
        role
    }
}

Now we get:

Solving Invalid User ID Issue

400 Bad Request

A 400 Bad Request error is thrown when there is a syntax error in the query and it indicates that the server refuses to process the query because of the error in the client’s request.

GraphQL already provides some level of help through type-checking to prevent this error. And once a query has an incorrect syntax, it is underlined with red squiggles in Altair.

Consider the code below:

query{
    user(id: 1, password: "12345") {
        username
        email
        password
        role
    }
}

In the user query, we only need an id argument, but the above query provides an additional password argument.

Running this query blindly would result in the 400 Bad Request as seen below:

400 Bad Request

Conclusion

Altair is a great GraphQL API client that is gaining traction. You can get a list of all Altair’s features here.

In this article, we learned how to debug GrapqhQL APIs by using the Altair developer tool, which is the Chromium developer tool.

It is important to note that we only focused on debugging client-side GrapqhQL. GraphQL logic such as our resolvers cannot be debugged on the client-side using Altair as this runs on the server — and in our example app, a Node.js server. So, debugging this server-side GrapqQL could be done with something like VSCode.

I hope you learned enough to give Altair a try in your next GraphQL project.

The post Debugging GraphQL with Altair appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/F4UGYwK
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top