Rust: How to consume REST API

Pudding Entertainment
5 min readJan 17, 2023

--

Photo by Luke Hodde on Unsplash

Rust is undoubtedly one of the most future-proof and promising languages to learn today. According to the Stack Overflow Developer survey it was named the “most loved programming language” every year from 2016 to 2022 and I have no doubt it will win in this nomination this year as well.

In this two-part tutorial we are going to implement a fully functional Rust binary telegram bot that will read two API endpoints, process the responses and send a message with an image to the given telegram chat.

Prerequisites

I’m using Rust version 1.66.0. This tutorial assumes prior knowledge of Rust and concentrates more on practical usage of the language. If you haven’t worked with certain topics before, it is advised to fill the knowledge gap upon tutorials completion.

As always, project sources are available at GitHub, find the link at the end of the page.

There are 3 parts in this tutorial: Project setup, Project architecture and REST API processing.
Next tutorial will cover Telegram bot message sending, image processing and a very basic build and run process.

Background

Before jumping into the tutorial itself allow me to give a bit of introduction into the project.

There is a web3 game called Illuvium Zero, it is a city builder that you can experience for free, once released. But being a crypto project, it also offers a way to contribute to the local economy and rip potential benefits out of it (Not financial advice). In order to do so one needs to purchase a plot of land using cryptocurrency. The first open land sale took place in June 2022 and the only way to get yourself a land today is to buy it off the open market using Illuvium Illuvidex or ImmutableX marketplace. Since it is an open market any landowner can put their plot on sale for whatever price they deem reasonable.
That’s exactly what we are going to track with the bot created out of these two tutorials.
All land transactions are processed using Layer 2 solution ImmutableX and they provide an API to track NFTs movements.

End result will look like this:

It is not very pretty but it gives enough information for a potential land buyer.

Part 1. Project setup

Let’s start off by defining all the required dependencies for the project.

This tutorial uses a particular API which has its own unique “flavors”. Luckily, by now there are a huge amount of crates available for Rust, so that we can concentrate on how to use the given crate rather than writing the “low-level” functionality from scratch.

For the needs of this application, the following Cargo.toml configuration will be used:

The [package] and [[bin]] parts are self-explanatory.

As per the [dependencies] part, here is why those crates were added:

  • log, env_logger — for, well, logging
  • reqwest, tokio — for REST API processing
  • futures — for multithreading execution
  • serde — for JSON response model
  • chrono — for dates parsing
  • teloxide — for telegram bot
  • rand, resvg — for image processing

Now that we have all the required dependencies added let’s look into the overall architecture of the project.

Part 2. Project architecture

To come up with a good architecture we should know how to use the ImmutableX API in order to retrieve the data. I’ll save you the hussle of reading through their documentation — the following two API endpoints will be called:

  1. /orders — to retrieve all orders:
  2. /assets/{token_address}/{token_id} — to retrieve the given asset/token metadata

Both responses have a well defined structure, and we can already create two models for them:

Note! There are more fields available in each API response, here only those that will be used later are added.

Both files will be placed under the model module

Next, let’s add a module responsible for calling the endpoints and processing the responses:

Lastly, we should reference all the created modules in main:

Note! Rust modules is quite a complicated topic even for experienced developers as it works very differently from other languages. If you are confused about how it all works — check out this video where this concept is brilliantly explained.

Part 3. REST API processing

Now that we have our architecture laid out it is time to get down to implementation. As mentioned previously, in order to call the endpoints the tokio library will be used.

Note! I assume prior familiarity with this library, but if you are new to it — please take a look at official documentation.

Let’s open new_listing_api_reader.rs module and write code to call the orders endpoint and process the response:

This is probably the most straightforward implementation of get request one can come up with. There are a few obvious drawbacks here, but those will be addressed later.

Now let’s throw in the second endpoint processing to finish new_listing_api_reader.rs. As of time of writing ImmutableX API doesn’t support any kind of Publish/Subscribe style, thus the API will be queried every minute to check the data for the last minute.

If you run the application now you should be able to see the response logged.
Well done!

Note! For simplicity’s sake certain edge cases (e.g. more than 100 newly listed lands in the last minute) were omitted from implementation.

But we are not stopping here. There are two major drawbacks to address:

1. Usage of unwrap() function is generally discouraged because it would just panic (aka crash the application). For API calling and parsing a proper error case handling should be implemented instead. There are different ways to achieve this. Here I wanted to encapsulate all the logic, including error handling, in the module itself. Thus, a helper function to call the API will be created.

2. By default the orders API returns 100 results, in order to make our application more performant, all of those can be processed in parallel. To do so we will take advantage of the futures crate.

With those changes applied, the application is now much safer and more performant.

Afterwards

REST API is a foundation of the majority of enterprise software ever created. Knowing how easy it is to create a fully functional, performant and robust application in Rust you should be definitely considering it for your next big project.

All of the code (including part 2) can be found at this GitHub repository.

Check out the second part of the tutorial— Rust: How to create Telegram bot.

Special thanks to my dearest friend and comrade Andrei Kochemirovskii for code review and valuable inputs.

Support

If you like the content you read and want to support the author — thank you very much!

Here is my Ethereum wallet for tips:

0xB34C2BcE674104a7ca1ECEbF76d21fE1099132F0

--

--

Pudding Entertainment

Serious software engineer with everlasting passion for GameDev. Dreaming of next big project. https://pudding.pro