Fetch API && Using public API for beginners in details 超详细超小白贴

Thu, Jun 4, 2020 3-minute read

Fetch API

API a computing interface, as a newbie I get confused about it a lot, like how to fetch data from a website. So I write down some notes to help understanding how to apply api


html setup

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,  initial-scale=1.0" />
    <title>Fetch API Sandbox</title>
  </head>
  <body>
    <button id="getText">Get Text</button>
    <button id="getUsers">Get JSON</button>
    <button id="getPosts">Get API DATA</button>
    <hr />
    <div class="" id="output"></div>
    <form id="addPost">
      <div class="">
        <input type="text" placeholder="Titile" id="title" />
      </div>
      <div class="">
        <textarea placeholder="Body" id="body"></textarea>
      </div>
      <input type="submit" value="submit" />
    </form>
    <script>
      document.getElementById("getText").addEventListener("click", getText);
      document.getElementById("getUsers").addEventListener("click", getUsers);
      document.getElementById("getPosts").addEventListener("click", getPosts);
      document.getElementById("addPost").addEventListener("submit", addPost);

method 1: use text way

 <button id="getText">Get Text</button>
      function getText() {
        // fetch("sample.txt")
        //   .then(function (res) {
        //     return res.text();
        //   })
        //   .then(function (data) {
        //     console.log(data);
        //   });
        fetch("sample.txt")
          .then((res) => res.text())
          .then((data) => {
            document.getElementById("output").innerHTML = data;
          })
          .catch((err) => console.log(err));
      }

method 2: use json way

      function getUsers() {
        fetch("Users.json")
          .then((res) => res.json())
          .then((data) => {
            let output = "<h2>Users</h2>";
            data.forEach(function (user) {
              output += `
            <ul>
            <li> ID:${user.id} </li>
            <li> Name:${user.name} </li>
            <li> Email:${user.email} </li>
            </ul>
            `;
            });
            document.getElementById("output").innerHTML = output;
          });
      }

---

## `method 3: getPost`

      function getPost() {
        fetch(`url`)
          .then((res) => res.json())
          .then((data) => {
            let output = "<h2>Posts</h2>";
            data.forEach(function (post) {
              output += (
                <div>
                  <h3> ${post.title}</h3>
                  <p>${post.body}</p>
                </div>
              );
            });
          });
      }

      function addPost(e) {
        e.preventDefault();

        let title = document.getElementById("title").value;
        let body = document.getElementById("body").value; if (firstName == null || firstName.isEmpy()) {
         	if (lastName == null || lastName.isEmpty()) {
             	return "";
            }
            return lastName;
        }
        return firstName + " " + lastName;

        fetch("url", {
          method: "post",
          headers: {
            Aceept: "application/jason, text/plain, */*",
            "Content-type": "application/json",
          },
          body: JSON.stringify({ title: title, body: body }),
        })
          .then((re) => res.json())
          .then((data) => console.log(data));
      }
    </script>

  </body>
</html>

---

## **using a public API for beginners JQuery version**

### ** jQuery 方法使用 api**

####`open the openweather website`

[openWeather](https://openweathermap.org/api)

> Get Started &nbsp; **`API`**&nbsp; Pricing &nbsp;Maps &nbsp;Partners&nbsp; Blog

> **`current weather data`**

\*\* `just sign in get your own API Key`注册好拿到免费的 api  key 开始

> api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key}

`replace your city name and appID, remove both {};`
this is mine version, 我拿东京和 key 示范后的网址

> api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=12d275b700d87f6629177d1dc84190bc

`open this url`把网址拷贝后看到网页呈现出这副德行

```bash
{"coord":{"lon":139.69,"lat":35.69},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":300.92,"feels_like":304.23,"temp_min":298.15,"temp_max":304.26,"pressure":1006,"humidity":83},"visibility":10000,"wind":{"speed":4.1,"deg":160},"clouds":{"all":20},"dt":1591320071,"sys":{"type":1,"id":8077,"country":"JP","sunrise":1591298748,"sunset":1591350838},"timezone":32400,"id":1850144,"name":"Tokyo","cod":200}

notice this “main : temp”, 300.92 this numer

"main":{"temp":300.92,

change the temp into imperial

把 temp 后面换个单位,变成我们看得懂的

api.openweathermap.org/data/2.5/weather?q=Tokyo&units=imperial&appid=12d275b700d87f6629177d1dc84190bc

add: &units=imperial to change the temp units

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>API</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="./script.js"></script>
    <link rel="stylesheet" href="./style1.css" />
  </head>
  <body>
    <div class="weather-container">
      <img src="" alt="" class="icon" />
      <p class="weather"></p>
      <p class="temp"></p>
    </div>
  </body>
</html>

now move on to the script.js


$.getJSON(
  "http://api.openweathermap.org/data/2.5/weather?q=Tokyo&units=imperial&appid=12d275b700d87f6629177d1dc84190bc",

  function (data) {
    console.log(data);
// try the code above ,
// my website shows :
// ....
// visibility: 10000
// weather: Array(1)
// 0:
// description: "scattered clouds"
// icon: "03d"
// id: 802
// main: "Clouds"


**now we need some icons to show the weather** 需要天气的小icons拉

search their icon webpage, get the url below:

> How to get icon URL
For code 500 - light rain icon = "10d". See below a full list of codes
URL is http://openweathermap.org/img/wn/10d@2x.png

check the information, weather, Array(1), icon : "03d", so the icon locates onn the weather[0];

try this code below:

var icon =
      "http://openweathermap.org/img/wn/" + data.weather[0].icon + ".png";
      console.log(icon);

    $(".icon").attr("src", icon);

  }
);

now add temp and weather:

var temp = Math.floor(data.main.temp);

var weather = data.weather[0].main;

 $(".weather").append(weather);

 $(".temp").append(temp);

one more steps: change another citys to check the weather ,换个城市看天气

var city = "Tokyo";

$.getJSON(
  // "http://api.openweathermap.org/data/2.5/weather?q=Tokyo&units=imperial&appid=12d275b700d87f6629177d1dc84190bc",
  "http://api.openweathermap.org/data/2.5/weather?q=" +
    city +
    "&units=imperial&appid=12d275b700d87f6629177d1dc84190bc",
  function (data) {
    console.log(data);

    var icon =
      "http://openweathermap.org/img/wn/" + data.weather[0].icon + ".png";
    // console.log(icon);

    var temp = Math.floor(data.main.temp);
    var weather = data.weather[0].main;
    $(".icon").attr("src", icon);
    $(".weather").append(weather);
    $(".temp").append(temp);
  }
);

done!!