TUTORIAL - Create a Crypto Coin Comparison Bot - BASIC - Part 3

in #utopian-io8 years ago (edited)

wallpaper.png

What Will I Learn?

Welcome to the third part of how to create a cryptocurrency coin comparison automatic posting bot for steemit ! In this part we will focus how we use request to make HTTP Request as a first step and afterwards how to connect the learned with the CoinMarketCap API to retrieve data for the first 10 cryptocurrency coins!

Requirements

Difficulty

  • Basic

Tutorial Contents

What is Request ?

Request is a simplified HTTP client, but what is HTTP and what is a HTTP Client ?

HTTP

HTTP stands for Hypertext Transfer Protocol which is basically the protocol you use to "surf" in the Internet.

HTTP Client

Most front-end applications communicate with backend services over the HTTP protocol. An HTTP client (Frontend) sends a request message to an HTTP server (Backend). The HTTP server answers with a response message to the client. So when Request says it is a simplified HTTP Client, it means it simplifies making HTTP Request and receiving HTTP Responses.

In the most Libraries which simplify HTTP Clients you just have to call a function for each different kind of HTTP Request and the magic happens in the background.

Before starting with some examples it is also important to understand which Request methods exists:

  • GET: Only Retrieve Data
  • POST: Send data to cause a change in state on the server
  • PUT: Replace complete data on server (of the target resource)
  • PATCH: Update data on server (of the target resource)
  • DELETE: Delete specified resource
    to name the common ones.

Using Request Examples

Now that we know what an HTTP Client is, I want to show examples for some of the Methods mentioned above (using request).

To use request inside our project we first need to add it at the top of our index.js file

var request = require('request');

THIS IS EXPLANATORY AND THE API ENDPOINTS DO NO EXISTS, MEANING TESTING IS NOT POSSIBLE

Let's assume we have an http server with following data on it:

{
  'bitcoin': {
    value: 9000,
    desc: 'A super stable coin, you should invest!'
  },
  'steem': {
    value: 0,5,
    desc: 'It sounds bad, do not invest!'
  }
}

Also does the server provide Endpoints for GET, POST, DELETE which are named the same.

With request it is possible to make requests on these endpoints.

GET

To call a GET Endpoint simply call request('ADRESS', function (error, response, body) {..})

request('http://www.oursuperapi.com/get?name=bitcoin', function (error, response, body) {
});

In our example we wanted to get the data for the object with name = bitcoin. Everything you can see after the ? is a parameter used in your GET Request. The server can get these parameters and decide which object he will return. For us he will return following:

{
  'bitcoin': {
    value: 9000,
    desc: 'A super stable coin, you should invest!'
  }
}

POST

After we retrieved the data for bitcoin we realized it is wrong and want to update it. We have three different options to do this POST, PATCH, PUT... The most common one is POST so we will stick to that. (PATCH & PUT are both used when you know the exact endpoint for the reference you want to change, in our example we do not know -> use POST)

We want to update our bitcoin value to 10000:

request({url: 'http://www.oursuperapi.com/post', method: 'POST', json: {name: 'bitcoin', value:'10000'}}, function(error, response, body){
});

A post request is a little bit different than the GET request request({url: 'ADRESS', method: 'POST', json: {DATA_WE_WANT_TO_POST}}, function(error, response, body){...});

DATA_WE_WANT_TO_POST is commonly named as body ! Remember when you want to change data with new data it is almost impossible that you do not provide a body containing the new data!

The same command is used for PATCH, PUT, etc... simply replace the method name accordingly. Also you could write request({url: 'http://www.oursuperapi.com/get', method: 'GET'}, function(error, response, body){...}); and it would work!

The value on our server would be now:

{
  'bitcoin': {
    value: 10000,
    desc: 'A super stable coin, you should invest!'
  }
}

DELETE

Now after changing the bitcoin data we want to delete the Steem data since it is completely wrong.
Delete methods can be used the same way as mentioned above request({url: 'http://www.oursuperapi.com/delete?name=steem', method: 'DELETE'}, function(error, response, body){...});. Just make sure that you use parameters instead of a body!

Connecting it with CoinMarketCap

If you came this far, we are ready to use our newly generated knowledge in our project!

We will create a new function, make a call to the coinmarketcap API to retrieve the last 10 coins and will print the response data out.

The CoinMarketCap API is pretty easy to use, since their endpoints are all GET Methods. In detail we want to call this API https://api.coinmarketcap.com/v1/ticker/?limit=10, it gives information about the first to 'limit' (tenth) coin. The data returned looks like this:

[
    {
        "id": "bitcoin",
        "name": "Bitcoin",
        "symbol": "BTC",
        "rank": "1",
        "price_usd": "573.137",
        "price_btc": "1.0",
        "24h_volume_usd": "72855700.0",
        "market_cap_usd": "9080883500.0",
        "available_supply": "15844176.0",
        "total_supply": "15844176.0",
        "percent_change_1h": "0.04",
        "percent_change_24h": "-0.3",
        "percent_change_7d": "-0.57",
        "last_updated": "1472762067"
    },
]

Optional parameters for the endpoint are:

  • (int) start - return results from rank [start] and above
  • (int) limit - return a maximum of [limit] results (default is 100, use 0 to return all results)
  • (string) convert - return price, 24h volume, and market cap in terms of another currency.

Implement it

Add it at the bottom of your file.

getTop10Coins();
function getTop10Coins() {
    request('https://api.coinmarketcap.com/v1/ticker/?limit=10', function (error, response, body) {
        if (error) {
            console.log('error:', error);
        }
        
        console.log('body:', body);
    });
}

Screen Shot 2018-02-20 at 09.38.56.png

In the next tutorial we will connect the retrieved data with mustache.js and create a more beautiful look of our output :)

I hope you liked it.

Curriculum

@Moderators

My first two tutorials of this series did not get accepted. I did some changes now and connected this tutorial part with the repository it is about (request). I gave a big introduction since this is important to understand how HTTP Requests work. I had to cut the actual usage of coinmarketcaps data to a new tutorial to make the post a bit shorter and not to overhelming. I hope this is okay, since the tutorial provide examples how to use request + one example everybody can test at home.
It would mean a lot if this part gets accepted because it's a big effort to write it :)
Thanks.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Thank you @roj :)

Hey @roj, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Hey @moonrise I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 64041.49
ETH 1748.03
USDT 1.00
SBD 0.42