My Red Story #2 Red to interact with WEB API 2/2
Tags: red
Published: 2021-01-02 06:46:03

---
title: My Red Story #2 Red to interact with WEB API 2/2
published: true
description: Coding story using Red-lang to interact with WEB API 2/2
tags: Red
series: My Red Story
//cover_image: https://direct_url_to_image.jpg
---

# Introduction

In my [previous post](https://dev.to/kobayu/my-red-story-1-make-a-tool-with-interacting-web-api-1-2-1oim), I describe Red's good points, mainly focused on non-functional aspects. In this post, I am talking about actual coding and some practices about using WEB API by Red.

Let's use [JSON Placeholder](https://jsonplaceholder.typicode.com)'s WEB APIs as example codes, that can be accessible for everyone.

## Calling Get API

The 1st example is just to `get` the "posts" data.

```red
read https://jsonplaceholder.typicode.com/posts
```

Ultimately easy! You have to do no package-installing, `import` or anything like that before running the code above. To look at the result, put `print` or `probe` before the code and execute it GUI console.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/709gjslfs2wx4djv520c.jpg)

## Calling with request headers

If you need to set a request header, you can use `write` function.

```red
write https://jsonplaceholder.typicode.com/posts [
    get [Content-type: "application/json; charset=UTF-8"]
]
```

The 2nd argument is a block that contains a http method name(like `get`, `post`) and an inner block that contains the header's key/value.

## Calling Post API with request body

When you have to set a request body value, you can add it as a JSON value after the header.

```red
json: to-json #(
    title: "foo"
    body: "bar"
    userId: 1
)

write https://jsonplaceholder.typicode.com/posts compose [
    post [Content-type: "application/json; charset=UTF-8"]
    (json)
]
```

Here is what the code does. `to-json` converts Red value to JSON string and `#( )` is a Red's `map!` type literal value to be converted. Then you can pass the JSON next to the request header. `compose` function is one of the Red's elegances. This function evaluates only inner words of `()`. Therefore after `compose` executed, the code line of calling `write` becomes below;

```red
write https://jsonplaceholder.typicode.com/posts [
    post [Content-type: "application/json; charset=UTF-8"]
    {{"title":"foo","body":"bar","userId":1}}
]
```

If you want the code shorter, you can do like below;

```red
write https://jsonplaceholder.typicode.com/posts compose [
    post [Content-type: "application/json; charset=UTF-8"]
    (
        to-json #(
            title: "foo"
            body: "bar"
            userId: 1
        )
    )
]
```

## Save response at any time

When you are making a program to interact with the WEB API of the other company, you might feel like to save the API response, because the response is not always stable. For example, WEB API often limits the number of calls during certain minutes and returns a 429 response when your API calls exceed it. In JSON Placeholder, the remaining count to call is set `X-Ratelimit-Remaining` header and if you exceed it, you have to wait until the time indicated by `X-Ratelimit-Reset` header. While you are writing code to handle this restriction properly, it is helpful to save API responses once you get it, instead of repeatable calling API until it gets over the limit. To get response header, you can use `read/info` or `write/info`. Here is a 'read' example;

```red
r: read/info https://jsonplaceholder.typicode.com/posts/1

save %response.red r
```

This code saves API response as a "response.red" file at the folder Red binary exists. The saved data is like this;

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2dpznbrfmmsw1uyxedn4.jpg)

I also put the saved data on my [GitHub Gist](https://gist.github.com/koba-yu/9973b450e30e3bd0d8ca311c9390bb4d)

This is a really understandable format. The 1st is the HTTP response code, the 2nd is the header represented by `map!` data type and 3rd is response body as a string. By the way, if you do not prefer for the 3rd value to be JSON, you can convert it to a Red value.

```red
r: read/info https://jsonplaceholder.typicode.com/posts/1
r/3: load-json r/3
save %response-2.red r
```

And here is the value to be saved: [GitHub Gist](https://gist.github.com/koba-yu/3fda709dae32c1c5cbab0fd125cda0c7)

So, you have saved response as a file, and you can restore it simply by doing this;

```red
r: load %response.red
```

This set the same value of the API response to a word `r` (in Red there is no variables but words). That's why you can resume your coding immediately even after you restart GUI console, without calling API again. When you want to test your code of handling a special condition, like when the limit number is 1 or 0 and you have to wait until the limitation is reset, just rewrite the value `X-Ratelimit-Reset` in "response.red" and load it. Then you can run the handling code and check the code behaves as you expect. As another choice, you can save 429 response after intentionally occurring it once.(Unfortunately, JSON placeholder's API seems not to return 429 response so I can not write an example data here). In any case, you are freed from calling API so many times.

# Seems great? Try Red!

I hope I could introduce the Red's attractiveness to you. If you want to check a more practical code with interacting WEB API, here is my [GitHub repo](https://github.com/koba-yu/ChatWorkKeeper). This code saves data from ChatWork(a popular business chat service in Japan) to local disk. I am still not an expert Red coder so any advice to the repo is welcome. Feel free to put a message on Issues, Discussions of the repo if you have something to talk with me.