Enhance your website with the use of an API

In this part of the course we are going to see how you can grab data from an external service, this is what we call using an API (Application Programming Interface).

API are services made available by other webmasters in order for you to build something on top of it. For example a weather forecast website may be interested in making available through an API all the data they are collecting. In exchange it makes their website/brand famous and/or they can also ask for money when many calls are made and/or when their data are very valuable.

Find below the code we are using in this tutorial.

<html>
<meta charset="utf-8">
<title></title>
<style>
    body {
        text-align: center;
    }

    form .startingline {
        font-weight: bold;
        margin-bottom: 10px;
    }

    label, input, .startingline {
        display: block;
        margin: 5px auto;
    }
</style><head></head>
<body>
<h1>Converter</h1>
<form>
    <div class="startingline">Current ...: <span id="price"><span id="conversion"></span></span> USD</div>
    <label for="satoshis">Satoshis</label>
    <input type="number" id="satoshis">
    <input type="button" value="Convert" id="submit">
    <label for="usd">US dollars</label>
    <input type="number" id="usd">
</form>
<h2>What?</h2>
<p>More text...</p>
<script>
    let input = document.getElementById("satoshis");
    let conversion;

    function convert() {
        console.log('input changed to: ', input.value);
        let output = input.value * conversion * 0.00000001;
        document.getElementById("usd").value = output;
    }

    fetch("https://blockchain.info/ticker?cors=true")
        .then(function(response) {
            return response.json()
        })
        .then(function(data) {
            document.getElementById("conversion").innerText = data.USD.last;
            conversion = data.USD.last;
            input.addEventListener('input', convert);
            document.getElementById("submit").addEventListener("click", convert)
        })
</script>
</body>
</html>


Last modified: Saturday, 28 September 2019, 1:23 PM