Consulting Temperature API with JS
Using javascript fetch to query an api
[Clique aqui para ler em português]
Let’s make a query for a temperature api using javascript fetch
Code
First let’s create the interface, we’ll do something simple, using just HTML.
To present the data we have a div with two spans, one to represent the city and the other to represent the temperature.
First of all you need to be registered on the openweathermap site, when you register you will have access to the key so just change the parameters in the js code.
In the constants we have city, a constant with the span city element and one with the span temperature element, then we have three support constants for the query, URL_MAIN (where the url of the openweather site is), API_KEY (where the access key is) and UNITS (where is the type of unit that will be returned from the api, for more information see the website).
To start, the browser’s own geolocation api is called, and with it the loadUrl function is called.
In the loadUrl function we get the coordinate that came from the geolocation api and we set the url to consult the api.
In the fetchApi function a query is made for the url that was created and when we have the api response it is displayed on the page with the innerText.
ready simple like that.
Demo
See below for the complete working project.
Youtube
If you prefer to watch it, see the development on youtube.
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
😊😊 See you later! 😊😊