第七课:API 与网络世界入门

连接真实互联网

API 的本质

到目前为止,你创建的所有网页都是"孤岛"——所有数据都是你自己写的。但你有没有想过: 天气网站怎么知道今天多少度? 新闻网站的新闻从哪里来? 股票软件的股价谁在更新? 答案就是:API(Application Programming Interface) API 的本质超级简单:
API = 一个网址 + 返回数据
当你访问一个普通网址(如 baidu.com),浏览器显示网页。 当你访问一个 API 网址,返回的是纯数据(通常是 JSON 格式)。 举个真实例子: 打开浏览器,访问这个网址:
https://api.github.com/users/octocat
你会看到这样的数据:
{
  "login": "octocat",
  "id": 583231,
  "avatar_url": "https://avatars.githubusercontent.com/u/583231?v=4",
  "name": "The Octocat",
  "company": "@github",
  "blog": "https://github.blog",
  "location": "San Francisco"
}
震撼吧! 这就是 API——一个返回结构化数据的网址。 学习资源: - [MDN - Web API 介绍](https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Client-side_web_APIs/Introduction) - [什么是 REST API](https://www.redhat.com/zh/topics/api/what-is-a-rest-api)

API 练习区

按 F12 打开浏览器开发者工具,在 Console 标签页中尝试本节的代码示例!

// 试试在控制台运行这行代码:fetch('https://api.github.com/users/octocat').then(r => r.json()).then(console.log)

试一试:在浏览器中访问 API

点击下面的链接,在新窗口中查看真实的 API 返回数据:

学习进度

已完成章节:0 / 23