Access API - "translate api example"

Got a LiveCode personal license? Are you a beginner, hobbyist or educator that's new to LiveCode? This forum is the place to go for help getting started. Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller

Post Reply
poco
Posts: 10
Joined: Mon Feb 22, 2021 10:15 pm

Access API - "translate api example"

Post by poco » Mon Apr 05, 2021 11:03 pm

I want to use LC and an api provided by CoinMarketCap-dot-com to fetch crypto coin data. I have successfully followed the LC tutorial found here (lessons dot livecode dot com /m/4071/l/1325310-how-to-request-a-resource-from-a-rest-api). (I'm limited in what I can post here.) So that simple api request example is working.

There are several examples of the use of the API found at the above noted website. However, I don't know how to "translate" those into calls made by LC. I am hoping someone here can show me how to do it - just translating one of the examples into a LC equivalent. Once I know how to do that, I think I will be able to read the api documentation and make other types of calls for different types of data.

By the way, I can already use the CURL example. I save it to an executable file, launch it, store the result in a file and read the file into LC. But, I was hoping for something more like the other examples that were given by the documentation for python, php, etc.

Any help is appreciated.

EDIT:

As a followup to the above post, I am experimenting with tsNetGet and tsNetGetSync. I've put the parameters into a LC array, but I don't know how to pass them to the api. Do I append them to the URL? (I tried that and it is not working so far.) Do I append them to the headers? (I don't know how I would format that.) It does not appear that there is any parameter for tsNetGet or tsNetGetSync that is intended to hold the parameters expected by the api. I assume I need to append them to the URL but using "?start=1&limit=5000&convert=USD" is not working.

Just FYI.

Thierry
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 875
Joined: Wed Nov 22, 2006 3:42 pm

Re: Access API - "translate api example"

Post by Thierry » Tue Apr 06, 2021 7:13 am

Hi Poco,

Let me believe this could help you:

You'll find a working curl command with some parameters:

Code: Select all

get shell("curl -X POST https://textbelt.com/text --data-urlencode phone='18001234'  --data-urlencode message='Hello world' -d key=textbelt")

and I did translated it to a POST livecode command only.

viewtopic.php?f=11&t=35604&p=203576#p203576

Of course, you'll have to adapt this script, and use your own parameters...

Kind regards,

Thierry
!
SUNNY-TDZ.COM doesn't belong to me since 2021.
To contact me, use the Private messages. Merci.
!

mrcoollion
Posts: 719
Joined: Thu Sep 11, 2014 1:49 pm
Location: The Netherlands

Re: Access API - "translate api example"

Post by mrcoollion » Tue Apr 06, 2021 9:24 am

I have already made a routine to get CoinmarketCap data and have slightly changed it for this post (hope all still works :shock: did not test any of it.)
Feel free to use it. Be aware that I have an Indy license and use tsNetGetSync.
Also make sure you have a field with name "Messages" to which the status of the call is pushed.
The data is in the array aCMC_Data .


Regards,

Paul

Code: Select all

------------------------------------------------------------------------------------------------------------------------------------------
// Get data from marketCap
// Make a fld with name "Messages"
------------------------------------------------------------------------------------------------------------------------------------------
Command GetCoinMarketCapData_V2  InAPIKey @OutErrorOrOk @aCMC_Data
   put empty into aCMC_Data["CoinMarketCap"]["Data"] 
   put empty into aCMC_Data["CoinMarketCap"]["Output"]
   --------------------------------
   put "https://pro-api.coinmarketcap.com" into tBaseURL
   put "/v1/cryptocurrency/listings/latest" into tEndPoint
   --put the milliseconds into tTicks
   put "" into tDataQueryString
   put InAPIKey into tAPIKey
   put tBaseURL&tEndPoint&"?"&tDataQueryString into tRequestString
   put "X-CMC_PRO_API_KEY: "&tAPIKey into tHeaders 
   ---------------------------------
   put "Getting CoinMarketCap Data" into tMessagetext
   put tMessagetext into fld "Messages" // Messages
   put tMessagetext into  aCMC_Data["CoinMarketCap"]["Output"]
   ---------------------------------
   put the ticks + 1458862263904 into tTicks1
   put tsNetGetSync(tRequestString, tHeaders, tRecvHeaders, tResult, tBytes) into tData
   -- tResult will be 200 (the HTTP response code for a successful transfer) if tsNetGetSync was able to retrieve the data
   -- If this is not the case, we will inform the user
   put the ticks + 1458862263904 into tTicks2
   put  cr & "tsNetGet request has completed, processing data in " & tTicks2-tTicks1 & " ms"  after aCMC_Data["CoinMarketCap"]["Output"]
   if tResult is not 200 then 
      beep 1
      put "Error" into OutErrorOrOk
      put cr & OutErrorOrOk & " Could not retrieve data from site"&cr&tData&cr&tResult after aCMC_Data["CoinMarketCap"]["Output"]
      put "Could not retrieve data with GetCandleHistorySync for coinpair "& InCoinpair into fld "Messages" 
      wait 1 seconds
      exit GetCoinMarketCapData_V2
   else 
      -- The retrieved data is in JSON format, convert to a normal LiveCode array
      put "Ok" into OutErrorOrOk
      ----
      put JSONtoArray(tData) into tArray //
      put tArray into aCMC_Data["CoinMarketCap"]["Data"] 
      -- Display the raw data in tOutput 
      put cr & "Succesfully retrieved Coin MarketCap Data" after aCMC_Data["CoinMarketCap"]["Output"]
      put "Succesfully retrieved Coin MarketCap Data" into  fld "Messages" 
      -- beep 1
   end if
end GetCoinMarketCapData_V2

poco
Posts: 10
Joined: Mon Feb 22, 2021 10:15 pm

Re: Access API - "translate api example"

Post by poco » Tue Apr 06, 2021 6:52 pm

Thank you both, Thierry & MrCoolLion!!!

A few comments:

MrCoolLion: Thank you. It works perfectly (and you didn't even test it!). I will study it to make sure that I know how it works (I'm pretty sure I do). Just as a test of my understanding, I modified it to change the number of records returned. Works great.

Thierry: I like your approach because I do not have to use the Indy version (which I may not have much longer). But I cannot get the POST command working.

I was able to successfully retrieve data in a couple ways (using LC Community +):

(1) Using `curl` to save a file to disk and then read it into LC
(2) placing all parameters on the query string (including the API key)
(3) placing the API key in a custom header and putting the parameters (start, limit, convert) on the query string.

BUT, I could never get the POST version working where I submitted my parameters (start, limit, convert) via a POST (as you did in your example). I just can't figure out what I am doing wrong on that score. I used your example as a guide but it still is not working. (I get a "not found" error.)

Thank you both again.

Thierry
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 875
Joined: Wed Nov 22, 2006 3:42 pm

Re: Access API - "translate api example"

Post by Thierry » Wed Apr 07, 2021 7:24 am

poco wrote:
Tue Apr 06, 2021 6:52 pm
Thank you both, Thierry & MrCoolLion!!!
Thierry: I like your approach because I do not have to use the Indy version (which I may not have much longer).
But I cannot get the POST command working.
Hi Poco,
It's a bit difficult to help you without seeing *how* you did code your solution.
Much better to put some code with to increase your chances to have some useful answers....

That said, I went to the coinmarket site, read the NodeJS, PHP and Python examples,
and with a wizard stick plus a crystal ball, and promess, without regex,
a voice from the dark told me to write this:

Code: Select all

constant APIkey = "!!!! PUT YOUR API-KEY HERE !!!!!!"
constant APIuri = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
constant APIpars = "?start=1&limit=100&convert=USD"

command getCoinMarketData
   local fullUrl, iAmRich, tableValues
   put APIuri & APIpars into fullUrl
   set the httpheaders to \
         "Accept: application/json" & CR & \
         "X-CMC_PRO_API_KEY: " & APIkey &CR
   put url fullUrl into iAmRich
   put JSONtoArray(iAmRich) into tableValues
end getCoinMarketData

Disclaimer: Not tested at all !!! (I don't have an API-Key)

Disclaimer2: if this code drop-down all the bitcoin markets, you're on your own :roll:

Thanks to let us know how you manage.


[Edited:] and to easily view the data:

Code: Select all

   if the result is empty then
      put JSONtoArray(iAmRich) into tableValues
      -- the widget is a tree view:
      set the arraydata of widget "ViewBitcoins" to tableValues
      ....
Thierry
!
SUNNY-TDZ.COM doesn't belong to me since 2021.
To contact me, use the Private messages. Merci.
!

Thierry
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 875
Joined: Wed Nov 22, 2006 3:42 pm

Re: Access API - "translate api example"

Post by Thierry » Wed Apr 07, 2021 8:28 am

Hi again,


Actually, we can test most of the API, even without a key.
Now, I can tell you I'm quite confident that it should work with a valid Key.

So, running this code:

Code: Select all

   ...........
   put url fullUrl into iAmRich
   
   if the result is empty then
      put JSONtoArray(iAmRich) into tableValues
      set the arraydata of widget "ViewBitcoins" to tableValues
      put "Done!" into fld 1
   else
      put the result &CR into fld 1
      -- TODO: check if we have something in iAmRich
      put JSONtoArray(iAmRich) into tableValues
      set the arraydata of widget "ViewBitcoins" to tableValues
      put "Done but wrong!" after fld 1
   end if
I end up with this beautiful error status:

screenshot-04-07.jpg
using a tree view widget

Kind regards,

Thierry
!
SUNNY-TDZ.COM doesn't belong to me since 2021.
To contact me, use the Private messages. Merci.
!

poco
Posts: 10
Joined: Mon Feb 22, 2021 10:15 pm

Re: Access API - "translate api example"

Post by poco » Wed Apr 07, 2021 3:42 pm

Thierry, thanks again for the example. I was able to successfully download data placing the API key in the custom header and the parameters on the query string (as you just did in your example). I have a method called "getViaQuery" to accomplish that. But I also tried submitting the parameters via a post request (using a method called "getViaPost"). Unfortunately, that returns a "404 Not Found" error. I do not know why.

Code: Select all

on getViaPost
   -- get api data via post request
   setCustomHeaders
   put "start=1&limit=5&convert=USD" into pParams
   
   post pParams to URL "<the_same_URL_you_used"
   put it into tJSON
   put jsonToArray(tJSON) into tArray
   set the arrayData of widget "tvData" to tArray
end getViaPost
It's not terribly important to fix this. After all, I can get the data now by just appending the parameters to the query string. But it is just annoying that I cannot successfully do it this other way by sending the parameters via a POST.

Thierry
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 875
Joined: Wed Nov 22, 2006 3:42 pm

Re: Access API - "translate api example"

Post by Thierry » Wed Apr 07, 2021 5:00 pm

But I also tried submitting the parameters via a post request (using a method called "getViaPost").
Unfortunately, that returns a "404 Not Found" error. I do not know why.
Hi Poco,

all the samples, including the curl command, are using a GET in the docs.
What's telling you that the POST is part of the API?
My guess is it is not.

Kind regards,

Thierry
!
SUNNY-TDZ.COM doesn't belong to me since 2021.
To contact me, use the Private messages. Merci.
!

poco
Posts: 10
Joined: Mon Feb 22, 2021 10:15 pm

Re: Access API - "translate api example"

Post by poco » Wed Apr 07, 2021 6:40 pm

Well, it looks like I am on the verge of learning something new. I thought that the ability to process a POST' was just "inherent" in servers; they were "programmed to handle that". So, I thought it was pretty much optional whether I submitted parameters via the query string or via POST. I now get the idea that I am mistaken. I need to have a better understanding of what the server is expecting. I spent a good deal of time with the api documentation but my mistaken assumption caused me to miss that important detail, viz., that you have to provide the parameter in the way that the server expects it to be provided - it is not simply the user's choice.

I REALLY appreciate all of your help!

Thierry
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 875
Joined: Wed Nov 22, 2006 3:42 pm

Re: Access API - "translate api example"

Post by Thierry » Thu Apr 08, 2021 6:58 am

poco wrote:
Wed Apr 07, 2021 6:40 pm
Well, it looks like I am on the verge of learning something new.
I REALLY appreciate all of your help!
You're welcome Poco :)

So, that's a good feeling, no?
At least, I enjoy these moments...
I spent a good deal of time with the api documentation
but my mistaken assumption caused me to miss that important detail,...
not sure it will help you, but I found their documentation a bit too verbose,
diluting the important information.

Are you aware that you should also send an Accept-Encoding: deflate, gzip header
to receive data fast and efficiently.

Good luck with your project!

Thierry
!
SUNNY-TDZ.COM doesn't belong to me since 2021.
To contact me, use the Private messages. Merci.
!

poco
Posts: 10
Joined: Mon Feb 22, 2021 10:15 pm

Re: Access API - "translate api example"

Post by poco » Fri Apr 09, 2021 2:40 am

Are you aware that you should also send an Accept-Encoding: deflate, gzip header
to receive data fast and efficiently.
Yes, I had read that in the documentation and was aware that I should include the header "Accept-Encoding: deflate, gzip".

However, even my working version (where I made a GET request) did not work when I included that additional custom header. I did not know why (basically because I did not understand its purpose). I just commented out that line.

I have since re-added that header and I now know why it was failing. It is returning compressed data and I am not properly handling that. Duh! :oops: :lol:

So, I guess it's time to look into LiveCode's "decompress" command!

Thanks again for your help.

EDIT: And, the new custom header and "decompress" is now working! :D

Post Reply

Return to “Getting Started with LiveCode - Complete Beginners”