🏄‍♂️ Insomnia: Quick & easy API development and testing
Tags: beginners, tutorial, testing, showdev
Published: 2021-09-20 15:53:26


## Introduction

Hello, DEV World! 👩‍💻👨‍💻 

In this article, I'm going to tell you some useful techniques for developing and testing APIs in Insomnia, so you can start applying them to your work every day.

> ☝️ If this is the first time you've heard about **Insomnia**, I'll give you a quick reference. So, [Insomnia](https://insomnia.rest/) is an open-source, cross-platform API Client for GraphQL, REST, and gRPC. Available for Mac, Windows, and Linux.

<a name="toc"></a>
### 📝 Table of contents

- [Postman VS Insomnia](#postman-vs-insomnia)
- [Use environment variables](#use-environment-variables)
- [Use data from other responses](#use-data-from-other-responses)
- [Use timeline tab for the research of request](#use-timeline-tab-for-the-research-of-request)
- [Troubleshooting](#troubleshooting)

<a name="#postman-vs-insomnia"></a>
## Postman VS Insomnia

In fact, there is no “confrontation” between these two wonderful tools, sorry!

Everyone chooses what is closer and more comfortable to her/him for everyday tasks. I will just give my reasons why, _for me personally_, Insomnia is a much _better_ performing API client than [Postman](https://www.postman.com/).

> 🤗 Please note: This is just my opinion, if you are satisfied with Postman, then I am truly happy for your choice.

**Pros of Insomnia** (_against Postman_):

- Application speed;
- User-friendly interface of the application;
- Functionality to use dynamic data from the responses of one API request in the scenarios of another request (within the same collection);
- Ability to customize the usual “IDE-like” fonts;
- Many great plugins from the community that extend the capabilities of the main application;
- A variety of excellent design themes (by the way, the “One Dark” theme used in the screenshots of this article);

**Cons of Insomnia** (_against Postman_):

- Slightly more aggressive paid subscription model (every day, a small banner will appear in the bottom-right corner of the app screen urging you to upgrade to a paid plan);
- Not so great possibilities for organizing multi nested API collections (there is only separation by different folders);
- Probably not as “pixel perfect” design as we would like (this can be seen in the app settings);

[↑ Table of contents](#toc)

<a name="#use-environment-variables"></a>
## Use environment variables

One of the most important things about designing, developing, and testing a REST API is the ability to quickly see the results in different environments.

Insomnia copes with this task, in my opinion, better than all analogues. Go to **Manage Environments** section, create a new **Sub Environment**, or add everything to the global ones. The notation for creating variables is simply JSON, which you can use for structures for variables of any nesting! 

You can also add a color to help you quickly identify the right environment from the list (_especially when you have a lot of them_).

![Env vars 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ho799goqpoxnr6go7clz.png)

They are now available in a handy switch in the upper-left corner of the main application screen. To call the environment variable, start writing `_.` (the underscore with a dot) in the right place. Insomnia will tell you which variables are available for the selected environment.

![Env vars 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kjsyjzj6ayykc35l5wt.png)

In my example from the screenshot, I've these variables:

```json
{
 "base_urls": {
  "v1": {                              // <-- version
   "auth": "http://127.0.0.1:5000/v1", // <-- auth server
   "api": "http://127.0.0.1:5000/v1"   // <-- api server
  }
 }
}
```

> ☝️ Don't be confused by the fact that both of my servers have the same local address `http://127.0.0.1:5000/v1`! Since I work with microservices, it's easiest to test them locally on the same address and port. On production, of course, they'll have radically different addresses.

If I want to put the base URL for my auth server in the query, I just say:

```console
_.base_urls.v1.auth
```

And voilà! 😉 According to my rough observation, this operation alone serves to perfectly increase the speed of the REST API developing.

[↑ Table of contents](#toc)

<a name="#use-data-from-other-responses"></a>
## Use data from other responses

The next very cool thing in Insomnia is the built-in function of transferring the received data from the body of one API response to the request of another. It's probably not clear in this explanation, let me explain it with a simple example.

If you have a closed part of the API methods, which are available only after passing the [JWT](https://jwt.io/) check, you may encounter a problem when testing. 

And you will always need to:

1. Authenticate the user to generate a valid JWT;
2. Copy this JWT into another API method;
3. Make a request;

Isn't that too much to do? 🤔 Thanks to Insomnia, we can shorten this process!

First, let's decide from which response body we want to take the token. In my case, it is the method that is available on the `/v1/user/login` endpoint. If authorization is successful, a response will be returned that contains the following:

![Data from response 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vapwp3es5xpoy8kpnufn.png)

Good! Now we have to define the place where we will insert this token. I have a private method in my test project to change the user's attributes, located on the `/v1/user/update/attrs` endpoint. That's where we will use the received token.

Go to the authorization settings, choose the auth type, and in the field with the value enter the word “body”. Insomnia will offer many options for placeholders, choose “Response ⇾ Body Attribute”:

![Data from response 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36yg669pb65lrt0w8cql.png)

Next, select the desired settings from where to get the data (specify the endpoint where the user authorized) and enter the path to the data in this notation (in the “Filter” field):

```console
$.jwt.token
```

Thereafter, Insomnia should show the data that it will insert:

![data from response 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0cacx7v06mkur3cngxlv.png)

That's it! 🤩 Now all you have to do is authorize, and the received JWT will be inserted automatically to this endpoint.

[↑ Table of contents](#toc)

<a name="#use-timeline-tab-for-the-research-of-request"></a>
## Use timeline tab for the research of request

Another of Insomnia's coolest features is the full timeline view of the request: what was sent, with what headers, what came in response, and how long. 

In my daily work, I often use this opportunity. Because it's great for figuring out where something might have gone wrong:

![Timeline](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ivf2r5ls60bklcpg8np5.png)

[↑ Table of contents](#toc)

<a name="#troubleshooting"></a>
## Troubleshooting

Every so often, when you test the API locally, requests for which must be authorized via a header with JWT (and it’s updated must be via a cookie with a refresh token), you may get an error: `refresh token not provided` (although it's in Insomnia cookie settings).

This happens because you use `Secure` cookie to store the refresh token, but you send a local request without HTTPS (i.e., not secure).

> 🤓 Read more about why this happens in [this](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security) article.

To be able to work with such endpoints, just turn off `Secure` in the cookie settings, like this:

![secure cookies](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cf9v3vpuv4xwvv0ksv0j.png)

[↑ Table of contents](#toc)

<a name=""></a>
## Photos and videos by

- Insomnia authors feat. Vic Shóstak

<a name=""></a>
## P.S.

If you want more articles (like this) on this blog, then post a comment below and subscribe to me. Thanks! 😻

And of course, you can help me make developers' lives even better! Just connect to one of my projects as a contributor. It's easy!

My projects that need your help (and stars) 👇

- 🔥 [gowebly][gowebly_url]: A next-generation CLI tool for easily build amazing web applications with Go on the backend, using htmx & hyperscript and the most popular atomic/utility-first CSS frameworks on the frontend.
- ✨ [create-go-app][cgapp_url]: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command.
- 🏃 [yatr][yatr_url]: Yet Another Task Runner allows you to organize and automate your routine operations that you normally do in Makefile (or else) for each project.
- 📚 [gosl][gosl_url]: The Go Snippet Library provides snippets collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance.
- 🏄‍♂️ [csv2api][csv2api_url]: The parser reads the CSV file with the raw data, filters the records, identifies fields to be changed, and sends a request to update the data to the specified endpoint of your REST API.
- 🚴 [json2csv][json2csv_url]: The parser can read given folder with JSON files, filtering and qualifying input data with intent & stop words dictionaries and save results to CSV files by given chunk size.

<!-- Footer links -->

[gowebly_url]: https://github.com/gowebly
[cgapp_url]: https://github.com/create-go-app
[yatr_url]: https://github.com/koddr/yatr
[gosl_url]: https://github.com/koddr/gosl
[csv2api_url]: https://github.com/koddr/csv2api
[json2csv_url]: https://github.com/koddr/json2csv