免费创建您自己的 API 的简单方法

2025-05-28

免费创建您自己的 API 的简单方法

目录

介绍

应用程序接口 (API) 是一组用于构建软件应用程序的例程、协议和工具。API 指定软件组件的交互方式。它可用于创建新的 API 或扩展现有的 API。API 可以是完全定制的、特定于某个组件的,也可以是基于行业标准设计的,以确保互操作性。API 可以是完全定制的、特定于某个组件的,也可以是基于行业标准设计的,以确保互操作性。

什么是 Google 表格?

Google Sheets是一款电子表格程序,包含在 Google Drive 服务中提供的免费网页办公软件套件中。它支持在线和离线协作编辑电子表格,并支持将电子表格存储在云端。它提供网页版、移动版和桌面版。

如何使用 Google Sheets 创建 API?

步骤 1

打开Google 表格并创建一个新的电子表格。

第 2 步

添加您想要在 API 中使用的数据。
图片描述

步骤3

点击分享按钮,即可与任何知道链接的人分享电子表格。* (请确保您已选择允许任何知道链接的人查看电子表格的选项)
图片描述

步骤4

现在单击帮助按钮并搜索AppScript,然后单击它以打开 AppScript 编辑器。这将在您的浏览器中打开一个新选项卡。

步骤5

这段代码是电子表格的 API。您可以根据自己的需求修改代码,还可以添加更多函数,使其更加实用。在本教程中,我们将使用以下代码。



function doGet(req){
  var doc=SpreadsheetApp.getActiveSpreadsheet();
  var sheet=doc.getSheetByName('Sheet1');
  var values =  sheet.getDataRange().getValues();
  var output=[];
  for(var i=0;i<values.length;i++){
    var row={};
    row['Name']=values[i][0];
    row['Location']=values[i][1];
    output.push(row);
  }
  return ContentService.createTextOutput(JSON.stringify({data: output})).setMimeType(ContentService.MimeType.JSON);
}


图片描述

步骤6

现在单击“部署”并选择“新部署”

步骤7

现在选择设置按钮。
图片描述

步骤8

现在单击“Web 应用程序”按钮并选择“谁有权访问该应用程序”作为任何人,然后单击“部署”
图片描述

步骤9

它会要求你授权该应用。点击“审核权限”,然后点击“允许”
(它会提示该网站未经验证。不用担心。只需点击“高级”,然后点击“前往应用”,即可安全授权该应用。)

步骤10

现在您将获得一个 URL。复制该 URL 并将其粘贴到浏览器中。您将获得 JSON 格式的数据。

太棒了🎉!您已经使用 Google 表格创建了自己的 API。

图片描述

创建示例网页来显示数据

  • 创建一个新文件并将其命名为index.html
  • 将以下代码添加到文件。```html

<!DOCTYPE html>





文档

const api="YOUR_API_URL";
fetch(api)
.then(response => respond.json())
.then(characters => showCharacters(characters.data));
showCharacters = characters => {

document.write("&lt;table class='tab'&gt;&lt;tr class='tab'&gt;&lt;th class='tab'&gt;&lt;h2&gt;Name&lt;/h2&gt;&lt;/th&gt;&lt;th class='tab'&gt;&lt;h2&gt;USN&lt;/h2&gt;&lt;/th&gt;&lt;th&gt;");
characters.forEach(character =&gt; {
    if(character.Name!="Name"){
  document.write("&lt;tr style='color:black;font-weight: bold;'&gt;&lt;td&gt;" + character.Name + "&lt;/td&gt;&lt;td class='tab'&gt;" + character.Location + "&lt;/td&gt;&lt;td&gt;");
  }
});
Enter fullscreen mode Exit fullscreen mode

}

- Be sure to replace **YOUR_API_URL** with the URL you got from the previous step.
- Now open the file in your browser and you will get the data in a table format.
- You can also use this API in your Android app or any other app.


## Conclusion

- In this tutorial, we learned how to create an API using Google Sheets.
- We also learned how to use the API in a web page.
- For reference, you can check out the [GitHub repository](https://github.com/Varshithvhegde/My_API) for this tutorial.  


If you have any doubts or suggestions, feel free to comment below.

文章来源:https://dev.to/varshithvhegde/easy-way-to-create-your-own-api-for-free-1mbc
PREV
如何使用简单的 JavaScript 创建文件共享网站
NEXT
Git 中分支和提交命名的简化约定