APIs,  JSON and you!

currently

If we want data or logic on our web page, we need to input the data, or we need to code the logic.

API

Application Programming Interface

HTTP Request

JSON

{
	"name": "Luke Skywalker",
	"hasRightHand":false,
	"gender": "male",
	"vehicles": [
		"x-wing",
		"snow speeder",
		"speeder bike"
	],
        "lightsabre":{
            "color":"green",
            "length":"2.5ft",
            "yearBuilt":"3 ABY"
        
        }
}

fetch

this is AJAX

promises

in action

 fetch("https://swapi.co/api/people/6")
    .then(resp => {
        console.log(resp)
    });
   

more complete example

 const request = () => {
    fetch("https://swapi.co/api/people/6")
        .then(resp => {
            if (resp.status === 200){
                return resp.json()
            } else {
                displayErrorMessage(resp)        
            }
        })
        .then(json => {
            displayData(json)
        })
}
   

but a modern approach is...

using async/await

 const request = async () => {
    const resp = await fetch("https://swapi.co/api/people/6")
    if (resp.status === 200){
          const json = await resp.json()
          displayDate(json)
    } else {
         displayErrorMessage(resp)        
    }
    

}
   

let's tell a joke!

Promises, APIs, Fetch, JSON

By Mark Dewey

Promises, APIs, Fetch, JSON

  • 505