Example 4 - Website queries, REST and JSON

Sometimes you need to fetch information from a website, either to display directly or to make a decision about what to display. Many websites accept requests and return data using the REST protocol. REST stands for REpresentational State Transfer, but it's not as daunting as it may seem. It's just a means of using standard HTTP commands - GET, PUT, POST and a few others - to send data to servers and retrieve it from them. Data is often transferred in the form of JSON (JavaScript Object Notation), which is why both sets of functions are present in this package. EasyCoder includes a set of functions for making queries and decoding what comes back.

Perhaps the most significant use of REST is to access data in WordPress itself. WordPress has a comprehensive REST interface - see more at WordPress REST API.

This example interrogates the EasyCoder website, where we've set up a demo 'endpoint' that returns a random number.


The URL is https://easycoder.software/ec/?random=1, which returns a number between 0 and 99 inclusive. You can test it by simply typing the URL into your browser's address bar. (If you want to do a lot of manual testing of server APIs we recommend you install Postman on your computer.)

You can also specify the range, as in


which returns a random number between 10 and 50 inclusive.

When you click the button the script requests a random number and displays it in the yellow box. This is obviously a very simplistic example - for more details see the documentation or ask us a question.

See also a more comprehensive example on our REST demo page.

<button id="ec-test">Test</button><span id="ec-response" style="margin:1em;border:1px solid blue;padding:1em;background-color:yellow">&nbsp;</span>

<!-- EasyCoder script ==============================================-->
<pre id="easycoder-script" style="display: none;">!
! Example 4
  button Test
  span Span
  variable Response

  attach Test to `ec-test`
  attach Span to `ec-response`
  on click Test
    rest get Response from `https://easycoder.software/ec/?random=1&low=10&high=50`
    set the content of Span to Response