api curl_具有cURL和JavaScript的Airtable API教程

api curl

If you're looking for a quick and easy way to persist your application data, look no further than Airtable. Airtable is basically an excel sheet like database that has tons of flexibility and a GUI for inspecting/creating data.

如果您正在寻找一种快速简便的方式来保存应用程序数据,那么Airtable就是您的最佳选择。 Airtable本质上是一个像数据库一样的Excel工作表,具有大量的灵活性和用于检查/创建数据的GUI。

I've used Airtable as the DB for a few of my demo apps recently, and I love it. There are other great options like Firebase, for example, but Airtable seems the easiest for me. In this article, let's explore how to create a base (Airtable's word for a database) and then perform CRUD (Create, Read, Update, and Delete) operations against it in two different ways, raw HTTP requests and the Airtable JavaScript package on NPM.

最近,我已经将Airtable用作我的一些演示应用程序的数据库,我喜欢它。 还有其他一些不错的选择,例如Firebase,但是Airtable对我来说似乎最简单。 在本文中,让我们探讨如何创建基础(Airtable的数据库词),然后以两种不同的方式对它执行CRUD(创建,读取,更新和删除)操作,即原始HTTP请求和NPM上的Airtable JavaScript包。

入门 ( Getting Started )

As with most products these days, you can sign up for free with Airtable. They do have a paid tier, but the free tier is more than enough and will probably last you a while. Sign up here

与如今的大多数产品一样,您可以免费使用Airtable进行注册。 他们确实有付费层,但免费层绰绰有余,可能会持续一段时间。 在此注册

Now that you're signed up, let's create our first base. You should be taken to a screen that displays all of your existing bases. I already have a few create that you can see here.

现在您已经注册,让我们创建我们的第一基地。 您应该进入显示所有现有基准的屏幕。 我已经有一些创建,您可以在这里看到。

For demo purposes, we are going to use an existing template instead of creating one from scratch. Click on Add a base. Then, choose Start With a Template.

出于演示目的,我们将使用现有模板,而不是从头开始创建模板。 单击Add a base. 然后,选择“ Start With a Template.

Let's use the Project Tracker template. After a few seconds, you should see your new base listed. Go ahead and open it up. Once you do, notice there is lots of dummy data in here.

让我们使用Project Tracker模板。 几秒钟后,您应该会看到列出的新基地。 继续并打开它。 完成后,请注意这里有很多虚拟数据。

I would suggest taking a few minutes to poke around here. A couple of things to notice while you do.

  • data is structured very similar to an Excel Sheet

    数据的结构与Excel工作表非常相似
  • column types are customizable (strings, numbers, dates, and lots more)

    列类型是可自定义的(字符串,数字,日期等等)
  • there are different tabs for different tables ("Design Projects" is selected by default)

    不同表格有不同的标签(默认情况下,“设计项目”处于选中状态)
  • you can even store an array of pictures as a property

    您甚至可以将图片阵列存储为属性

Just based on this dummy data, you get a quick feel for how cool Airtable is!

仅仅基于这些虚拟数据,您就可以快速了解Airtable多么酷!

API ( The API )

The documentation for Airtable is another plus. It walks through examples of all of the CRUD operations that you can perform on your data. You can find the API Documentation here.

Airtable的文档是另一个优点。 它遍历了可以对数据执行的所有CRUD操作的示例。 您可以在此处找到API文档

From there, select the base that we created a few minutes ago. The cool thing is that the documentation will now be specific to the data that is in that base.

从那里,选择我们几分钟前创建的基础。 很酷的事情是,文档现在将特定于该基础中的数据。

One thing to take a look at at the top of the docus page is the Rate Limit section. This explains the limitation on how many requests per second you can make to the API.

在docus页面顶部要看的一件事是“ Rate Limit部分。 这就解释了每秒可以向API发出的请求数量的限制。

"The API is limited to 5 requests per second per base"

“ API限制为每秒每基础5个请求”

You can also read more about the Pricing here.

您还可以在此处阅读有关定价的更多信息。

认证方式 (Authentication)

Like every other API, you'll need some sort of private credential to pass along in your API requests for Airtable to verify it. In this case, the private credential is an API Key. If you scroll to the Authentication section, it will tell you a little bit more.

与其他所有API一样,您需要某种私有证书才能在API请求中传递,以供Airtable进行验证。 在这种情况下,专用证书是API Key. 如果滚动到“ Authentication部分,它将告诉您更多信息。

As we scroll through the docs, I've got the show API Key checkbox checked. This is one of the easiest ways to find out what your key is. Although I'm sharing mine in these images, I'm going to change it by the time you read this.

当我们滚动浏览文档时,我已经选中了show API Key复选框。 这是找出密钥的最简单方法之一。 尽管我在这些图像中共享我的图像,但是在您阅读本文时,我将对其进行更改。

Never share your API keys with anyone

切勿与任何人共享您的API密钥

Your API Key will need to be passed as a bearer token in your Airtable requests. More on that in a second.

您的API密钥需要在您的Airtable请求中作为bearer token传递。 一秒钟内会更多。

设计项目表 (Design Projects Table)

As your scroll down through the docs you'll get to a section that shows you the details of the fields that you have in your base. If you started with the same template referenced above, this section is called Design Projects Table .

向下滚动文档时,您会看到一个部分,向您显示基础中字段的详细信息。 如果您从上面引用的相同模板开始,则此部分称为“ Design Projects Table

I just wanted to make one clarification for working with Airtable. Fields are referring to the properties that you specifically define for each one of your table. There are some properties that Airtable creates automatically (record id and created timestamp), but these are not included in fields. You'll see this in action below.

我只是想澄清一下使用Airtable的方法。 Fields指的是您为表中的每个表专门定义的属性。 Airtable会自动创建一些属性(记录ID和创建的时间戳),但这些属性未包含在fields. 您将在下面看到此操作。

API URL结构 (API URL Structure)

Here's how the API calls work. I'm using the specific details for my example

API调用的工作方式如下。 我在使用示例的具体细节

  1. base API url - https://api.airtable.com/v0/

    基本API网址-https: //api.airtable.com/v0/
  2. table id - appu53qW5mpKdJAW2

    表格ID-appu53qW5mpKdJAW2
  3. name of the table - "Design Projects"

    表格名称-“设计项目”

You put all of this together and you get something like this.

将所有这些放在一起,就得到了类似的东西。

https://api.airtable.com/v0/appu53qW5mpKdJAW2/Design%20projects

As mentioned earlier, you'll need to pass your API Key as a bearer token as well.

如前所述,您还需要将API密钥作为bearer token传递。

Postman中带有HTTP请求的CRUD操作 ( CRUD Operations with HTTP Requests in Postman )

Again, the docs are really good.

同样,这些文档确实很棒。

列出记录 (List Records)

Scroll down to the List Records section, and you can see how what the HTTTP request looks like to retrieve a list of records.

向下滚动到“ List Records部分,您可以看到HTTTP请求如何检索记录列表。

In the URL that they give you, can you see the different parts that we referenced above? Also included are a few query parameters for filtering.

https://api.airtable.com/v0/appu53qW5mpKdJAW2/Design%20projects?maxRecords=3&view=All%20projects

Let's give this a test. I'm going to use Postman for testing these HTTP requests.Inside of Postman, I choose to make a Get request, pass it the URL, and then include the API Key in the Headers section.

让我们对此进行测试。 我将使用Postman测试这些HTTP请求。在Postman内部,我选择发出一个Get请求,将其传递给URL,然后在Headers部分中包含API Key。

Each response from Airtable will return an object that has a property of
records which will hold all of the records that we have queried or udpated. It's nice and consistent!

records的属性,该属性将保存我们查询或删除的所有记录。 很好而且很稳定!

检索记录 (Retrieve a Record)

To retrieve a specific record, we simply pass the ID of the record we are looking for on to the end of the API and remove the query string parameter. You can grab one of the IDs out of the return body from the previous request. Here's my URL.

要检索特定记录,我们只需将要查找的记录的ID传递到API的末尾,然后删除查询字符串参数即可。 您可以从上一个请求中从返回主体中获取一个ID。 这是我的网址。

https://api.airtable.com/v0/appu53qW5mpKdJAW2/Design%20projects

You should get a response like this.

您应该会收到这样的答复。

建立记录 (Create a Record)

To create a record, we use the same base URL that we have been using.

要创建一条记录,我们使用与我们一直使用的相同的基本URL。

https://api.airtable.com/v0/appu53qW5mpKdJAW2/Design%20projects

The difference is that this becomes a POST request and we include the record(s) we want to include in the body of the request. To pass JSON data in Postman, I usually select raw and then JSON (application/json).

不同之处在于这将成为POST请求,并且我们将要包含在请求正文中的记录包括在内。 为了在Postman中传递JSON数据,我通常选择raw ,然后选择JSON (application/json).

Similar to the response that we get back from Airtable, we send an object that has a property called records and then a record for each item we want to create.

与从Airtable返回的响应类似,我们发送一个对象,该对象的属性为records ,然后为要创建的每个项目创建一个记录。

Notice in the return data that the record has two new properties, id and createdTime . This lets you know that the record was created successfully. You can also view your new record in the GUI to verify.

注意,在返回数据中,记录具有两个新属性, idcreatedTime 。 这使您知道记录已成功创建。 您也可以在GUI中查看新记录以进行验证。

更新记录 (Update a Record)

There are two different ways to update a record.

有两种不同的方式来更新记录。

  • PATCH - this will update an fields that are specified in the incoming record

    PATCH-这将更新传入记录中指定的字段
  • PUT - this is a destructive update that will clear any fields that aren't specified

    PUT-这是一个破坏性更新,将清除所有未指定的字段

You'll have to determine which of these makes more sense for you, but I'm going to show an example using Patch . Again, same base URL.

您必须确定其中哪一个对您更有意义,但我将使用Patch演示一个示例。 同样,相同的基本URL。

https://api.airtable.com/v0/appu53qW5mpKdJAW2/Design%20projects

The only thing I'm going to update in the body is the name to Testy Test Updated!! .

我体内唯一要更新的是Testy Test Updated!!的名称Testy Test Updated!!

{
    "records": [
        {
            "id":"recBW7Qan7p8eedRy",
            "fields": {
                "Name": "Testy Test Updated!!"
            }
        }
    ]
}

Check the GUI to see the updated record.

检查GUI以查看更新的记录。

删除记录 (Delete a Record)

Lastly, we can delete a record. We do this by sending a DELETE request and putting the record id on the end of the url.

最后,我们可以删除一条记录。 我们通过发送DELETE请求并将记录id放在url的末尾来实现。

https://api.airtable.com/v0/appu53qW5mpKdJAW2/Design%20projects?records[]=rec3u2SyIm7ZCktXU

The response that comes back verifies the record was deleted. You could also look in the GUI again.

回来的响应将验证记录已删除。 您也可以再次在GUI中查看。

使用JavaScript进行CRUD操作 ( CRUD Operations with JavaScript )

Alright, we got most of the details covered. Now, let's take a quick look at the Airtable package on NPM to see how to accomplish the same thing using JavaScript.

好了,我们已经涵盖了大部分细节。 现在,让我们快速看一下NPM上的Airtable包 ,看看如何使用JavaScript来完成相同的事情。

Since we are repeating steps, I'll skip images and just show code snippets.

由于我们正在重复步骤,因此我将跳过图像,仅显示代码片段。

设置和初始化 (Setup and Initialization)

In your favorite editor, open a folder and create a file called app.js. Then run the following command to initialize your project as a JavaScript project.

在您喜欢的编辑器中,打开一个文件夹并创建一个名为app.js.的文件。 然后运行以下命令将您的项目初始化为JavaScript项目。

npm init

Then install the Airtable package.

然后安装Airtable软件包。

npm install airtable

Now we need to initialize the Airtable object in our file.

现在,我们需要在文件中初始化Airtable对象。

  • require Airtable

    需要航空表
  • create a reference to our base using our API key and base ID

    使用我们的API密钥和基本ID创建对我们基础的引用
  • create a reference to our table using the base reference and the table name

    使用基本引用和表名称创建对我们表的引用
const Airtable = require('airtable');
const base = new Airtable({ apiKey: '<YOUR_API_KEY>' }).base(
    'appqvc1jKHBIRRbSy'
);

const table = base('Design projects');

For our CRUD operations, we will use the table variable from now on. Each call that we make will return a promise. I'm using the async/await pattern instead of .then() and .catch() to handle the returned promise.

从现在开始,对于CRUD操作,我们将使用table变量。 我们进行的每个通话都会返回一个承诺。 我使用的是async/await图案代替.then().catch()来处理返回的承诺。

获取记录 (Get Records)

Call the select() function which takes an object where you can include query parameters. Earlier, we used maxRecords and view , so we can do the same here.

调用select()函数,该函数接受一个可以在其中包含查询参数的对象。 之前,我们使用了maxRecordsview ,所以我们可以在这里做同样的事情。

After calling select() we also need to call firstPage() . This is because of pagination. If we have lots of record in our table, we probably don't want them all at one time, so we can call firstPage() to get the first page of results.

调用select()我们还需要调用firstPage() 。 这是因为分页。 如果表中有很多记录,则可能一次不希望全部记录,因此可以调用firstPage()来获取结果的第一页。

const getRecords = async () => {
    const records = await table
        .select({ maxRecords: 3, view: 'All projects' })
        .firstPage();
    console.log(records);
};

获取记录 (Get A Record)

To get a specific record, we can call find() and pass the ID of the record we are looking for.

要获取特定记录,我们可以调用find()并传递我们要查找的记录的ID。

const getRecordById = async (id) => {
    const record = await table.find(id);
    console.log(record);
};

If you log out the results here, you might notice that there is a ton of information that gets returned. One trick I use is to strip out all of the extra data except for id and fields. I created a minify function to do this.

如果您在此处注销结果,则可能会注意到有大量信息被返回。 我使用的一个技巧是去除idfields.之外的所有其他数据fields. 我创建了一个minify函数来做到这一点。

const minifyRecord = (record) => {
    return {
        id: record.id,
        fields: record.fields,
    };
};

With minify in place, my log output goes from this.

有了minify,我的日志输出就从这里开始。

to this...

为此...

Much cleaner right?

更清洁吧?

建立记录 (Create a Record)

To create a record, we call the create() function and pass an object to represent the fields of the record.

要创建记录,我们调用create()函数并传递一个对象来表示记录的字段。

const createRecord = async (fields) => {
    const createdRecord = await table.create(fields);
    console.log(minifyRecord(createdRecord));
};

更新记录 (Update a Record)

To update a record, call the update() function and pass the ID of the record and the fields you want to update.

要更新记录,请调用update()函数并传递记录ID和要更新的字段。

const updateRecord = async (id, fields) => {
    const updatedRecord = await table.update(id, fields);
    console.log(minifyRecord(updatedRecord));
};

删除记录 (Delete a Record)

To delete a record, call the destroy() and pass the ID of the record you want to delete.

要删除一条记录,请调用destroy()并传递要删除的记录的ID。

const deleteRecord = async (id) => {
    const deletedRecord = await table.destroy(id);
    console.log(minifyRecord(deletedRecord));
};

###

###

处理错误 (Handling Errors)

Anytime you make HTTP requests, you need to be prepared for handling errors. In each of the examples above, you should surround the API call with a try/catch so that you can handle errors if there are any.

无论何时发出HTTP请求,都需要为处理错误做好准备。 在上面的每个示例中,您都应在API调用周围加上try/catch以便可以处理任何错误。

const deleteRecord = async (id) => {
    try {
        const deletedRecord = await table.destroy(id);
        console.log(minifyRecord(deletedRecord));
    } catch (err) {
        console.error(err);
    }
};

结语 ( Wrap Up )

Hopefully, you can see how quick and easy it is to use Airtable in your applications. If you're using JavaScript, it's a no-brainer because the NPM package is so easy to work with. Not to mention, the overall documentation is really good as well.

希望您能看到在您的应用程序中使用Airtable的便捷性。 如果您使用的是JavaScript,那么这很容易,因为NPM软件包非常易于使用。 更不用说,整体文档也非常好。

Question for you. What kind of DB are you using for your applications? Let me know in the comments!

给你的问题。 您正在为应用程序使用哪种数据库? 在评论中让我知道!

翻译自: https://scotch.io/tutorials/airtable-api-tutorial-curl-and-javascript

api curl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值