Home >CMS Tutorial >WordPress >WP REST API to get data

WP REST API to get data

PHPz
PHPzOriginal
2023-09-04 14:05:01781browse

In previous parts of this series, we have been looking at what the WP REST API is and how it helps us build better applications using the WordPress backend.

We then looked at two different ways of setting up authentication on the server to generate authenticated requests. The first is the Basic Authentication method, which is useful in development environments and allows for rapid prototyping as it does not take much time to set up. The advanced authentication method is OAuth 2.0, which is recommended for production environments because it is much more secure than the basic authentication method.

Now that we understand how to set up authentication, we are ready to generate authenticated requests to unlock the full power of the WP REST API. We will use Basic authentication in this series due to its ease of use, but it is recommended that you use OAuth 2.0 authentication (provided by the WordPress REST API Authentication plugin) for your production servers.

The WordPress REST API Authentication plugin enhances the security of the WordPress REST API by adding an authentication mechanism to control access to API endpoints. It comes with some authentication methods:

  • Basic Authentication
  • API Key Authentication
  • JWT Authentication
  • OAuth 2.0 Authentication

After setting up authentication, you can define access control rules for different API endpoints. It allows you to configure which users or roles have access to specific endpoints. It also provides options to restrict access based on user roles, capabilities, or specific user IDs.

In this current installment of the series, we’ll get our first hands-on look at the WP REST API. we will:

  • Analysis GET Request structure
  • View OPTIONS How to request self-logging API
  • Send a request to the server to retrieve data
  • Analyze server response including attributes, schema and links
  • GET request analysis
  • Navigating the API using OPTIONS requests
  • Processing Posts
  • Using post revisions, categories and tags
  • Use other resources

Therefore, we first analyze the structure of a simple GET request.

GET Request Analysis

Before we delve into the details of retrieving any data using the WP REST API, we need to be familiar with the syntax of the request sent to the server. This will provide a solid foundation for our future interactions with the WP REST API.

Consider the following request sent to the server:

$GET https://localserver/wp-json/wp/v2/posts

The type of request we send is GET — one of the six HTTP verbs we covered in part one of this series. GET The request is used to retrieve data from the server. So when executed on the server, the above request retrieves a collection of all post objects as JSON data.

Considering the request URI, we can divide it into the following parts:

  • https://localserver/: The URL of my local development server. It can be any URL, depending on where your WordPress is installed.
  • /wp-json: Endpoint prefix for WP REST API.
  • /wp: The namespace of the WP REST API.
  • /v2: Version of WP REST API.
  • /posts: This is the resource we want to retrieve from the server.

Namespaces prevent overrides that can occur when running multiple plugins, each providing its own layer of abstraction for the RESTful API. Therefore, each abstraction works within its own boundaries and does not affect methods and properties belonging to other abstractions.

In addition to retrieving a collection of resources (posts) using the above URI, we can also retrieve a specific resource by mentioning its ID:

$GET /wp/v2/posts/100

The above request will return a post object because it looks down for the post resource with ID 100.

Usually, we also need to search for posts that meet certain specific conditions. For example, you can filter posts by category, as shown in the following code snippet.

$ GET /wp/v2/posts?categories=20,30

By sending the above request, we can retrieve all posts belonging to the categories with ID 20 and 30. As you can see, you can pass one or more category IDs in the categories parameter and it should return posts assigned specific terms within the category classification.

The above syntax is equivalent to the following WP_Query() call:

<?php
$query = new WP_Query( array(
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => array( 20, 30 ),
        ),
    ),
) );

Thus, the above GET request will retrieve a list of posts belonging to two categories with IDs 20 and 30. The same syntax can also be used for array parameters with more than two elements.

Now that we've seen how to format a GET request and provide its parameters, it's time to look at the OPTIONS request. OPTIONS Requests make it easy to navigate the API, and actually serve as a self-documenting way to make the API more accessible by logging all available HTTP methods on the endpoints along with the parameters they support.

Navigating the API using OPTIONS requests

As mentioned previously, OPTIONS requests are very helpful for exploring the API. It mentions all the endpoints belonging to a route and provides a list of parameters for which CRUD operations are supported by these endpoints.

Let's send an OPTIONS request to the /wp/v2/posts route to check what endpoints it supports and what data we can query along the GET request:

$curl -X OPTIONS /wp/v2/posts

I used curl to send the above request, but you can use any tool of your choice, including Postman. Be sure to include the full path to the above route, including the path to your server.

{
    "namespace": "wp/v2",
    "methods": [...],
    "endpoints": [...],
    "schema": {...},
    "_links": {...}
}

The above OPTIONS request /wp/v2/posts route returns data in JSON format, which contains five attributes:

  • Namespaces
  • method
  • Endpoint
  • schema
  • _links
{
    "namespace": "wp/v2",
    ....
}

namespace The attribute identifies the namespace of the current plugin. In our case, it’s wp/v2, which represents version 2 of the WP REST API. We already learned about the purpose of namespaces and their services in the previous section.

{
    ...
    "methods": [
        "GET",
        "POST"
    ],
    ...
}

methods 属性包含当前路由支持的所有方法的数组。通过查看上述请求返回的响应,可以清楚地看到 /wp/v2/posts 路由支持两种方法,即 GET POST 。这意味着我们可以使用 /wp/v2/posts 路由来检索帖子,以及创建新帖子。我们将在本系列的下一部分中处理 POST 方法,因此我们暂时只关注 GET 方法。

下一个属性 — endpoints — 包含当前路由支持的端点数组。此属性直接链接到前面提到的 methods 属性,因为它列出了支持的方法的端点。

{
    ...
    "endpoints": [
        {
            "methods": [
                "GET"
            ],
            "args": {...},
            "allow_batch": {"v1":true}
        },
        {
            "methods": [
                "POST"
            ],
            "args": {...},
            "allow_batch": {"v1":true}
        }
    ],
    ...
}

endpoints 属性包含对象值,而对象值又包含三个属性,即 methodsargsallow_batchmethods 属性包含 HTTP 方法的数组,下一个 args 属性包含这些方法支持的所有参数。最后,allow_batch 属性用于了解端点是否支持批量请求功能。这些是我们以 URI 参数的形式随请求发送的参数。

查看 GET 方法支持的参数,我们发现了 20 多个参数,包括 contextpagerequiredtypedefaultrequired 属性指示该参数是否为必需,而 default 属性表示该参数的默认值。另一方面, type 属性指示应传递的值的类型。除此之外,它还可能包含其他特定于参数的属性。

"methods": [
        "GET"
],
"args": {
    "context": {
        "required": false,
        "default": "view",
        "type": "string",
        "description": "Scope under which the request is made; determines fields present in response."
    },
    "page": {
        "required": false,
        "default": 1,
        "type": "integer",
        "description": "Current page of the collection.",
        "minimum": "1"
    },
    "per_page": {
        "required": false,
        "default": 1,
        "type": "integer",
        "description": "Maximum number of items to be returned in result set.",
        "minimum": "1",
        "maximum": "100"
    },
}

返回的响应中的 schema 属性记录了当前资源的所有属性。该架构定义了 JSON 格式的数据结构。 WP REST API 中使用的架构格式基于 JSON 架构规范草案 4。

最后一个 _links 属性包含一个对象数组,其中包含关联资源的链接。对象中的键指定关系类型(例如 authorcollectionselfcomments 等) ,其值是指向相关资源的链接。该链接标准基于 HAL(超文本应用语言)。您可以通过阅读 Mike Kelley 撰写的规范来了解有关 HAL 的更多信息。

以类似的方式,我们也可以向其他路由(包括用户、评论、媒体、页面等)发送 OPTIONS 请求,以检查其支持的方法和参数。 OPTIONS 请求是您使用 WP REST API 时最好的朋友。

WP REST API 提供了另一种评估 API 可用性的方法,即向 /wp-json 索引路由发送 GET 请求。这将列出所有路由及其端点及其支持的方法和参数。

$curl -X GET http://wordpress-server/wp-json

上述请求将返回一个包含路由属性的响应对象,如下所示:

获取数据的WP REST API

此功能非常强大,因为它列出了所有路由及其支持的方法和参数,因此无需在外部记录所有这些内容。当我们对不同的资源执行CRUD操作时,我们将引用这个响应对象。

查看了探索 API 的选项后,现在让我们开始使用 WP REST API 从服务器检索数据。

处理帖子

到目前为止,我们已经熟悉了 OPTIONS 请求,这是一种评估 API 可用性的自记录方式。我们还研究了它如何显示给定路由支持的方法和参数。利用这些知识,我们现在准备使用 WP REST API 从服务器检索不同的资源。

我们将从 <em>posts</em> 资源开始,因为它是 WordPress 的主要构建块。我们将使用不同的标准来检索帖子。通过应用这些知识,您将能够使用 WP REST API 查询帖子,就像使用 WP_Query 类一样。

在本系列中,我们一直在使用 <em>posts</em> 资源来演示示例请求及其响应,并且我们已经知道如何通过 ID 检索帖子集合和单个帖子。所以我们不会再讨论这个了。相反,我们将研究一些使用顶级参数检索帖子的更高级方法。

使用顶级参数

WP REST API 直接在 GET 端点上公开一些最常用的帖子查询变量。这些参数是:

parameter meaning
context Requested range. Possible values ​​are view, embed, or edit. Default is view.
page The current page of the post collection. Default is 1.
per_page Total number of posts per page. Default is 10.
search Search query. Limit results to matching strings.
after Return only posts published after the date specified in this parameter.
modified_after Return only posts modified after the date specified in this parameter.
author Author ID. Used to limit results belonging to a specific author.
author_exclude The result set does not include posts assigned to specific authors.
Before Return only posts published before the date specified in this parameter.
modified_before Return only posts modified before the date specified in this parameter.
exclude Array of post IDs to exclude from search results.
include Limit results to the post IDs specified in this array.
offset Offset the search results by the specified number.
order The order of the collection. Can be asc or desc.
orderby The sorting property of the collection. Possible values ​​are author, date, id, include, modified, parent, relevance, slug , include_slugs and title.
search_columns You can specify an array of column names to search.
<strong>slug</strong> Limit results to posts with a specific slug.
status Used to limit the collection of posts with a specific status.
tax_relation Used to limit the result set based on relationships between multiple taxonomies.
category Filter the result set by terms assigned within the category classification.
categories_exclude Filter the result set to items other than the specific terms specified in the category classification.
<strong>Label</strong> Filter the result set by terms specified in the tag classification.
tags_exclude Filter the result set to items other than the specific terms specified in the tag classification.
sticky is used to limit the result set to sticky items.

context 参数用于根据我们正在工作的范围获取帖子。如果我们只是在索引页面上列出帖子,那么我们可以使用 view 上下文。但是,如果我们要检索帖子以进行编辑,则需要使用 edit 上下文:

$GET /wp/v2/posts?context=edit

edit 上下文参数在 titlecontentraw 字段="inline">摘录。这个 raw 字段的值可以在编辑器中回显出来,用于编辑内容。

获取数据的WP REST API

使用 edit 上下文需要您作为具有 edit_posts 权限的用户进行身份验证。

使用 embed 作为 context 参数的值可获取帖子的集合及其属性的最小子集。

上面提到的其他参数非常不言自明,您可以在 HTTP 客户端中使用它们。

这些是允许您根据特定条件查询帖子的基本参数。

如何使用其他条件过滤记录

除了使用一些基本的顶级参数检索帖子集合之外,WP REST API 还允许您按各种其他条件过滤记录。通过使用此语法,我们可以像使用 WP_Query() 类一样查询帖子。

分页参数是所有过滤器中最重要的,因为它们在帖子列表页面上广泛使用。分页参数允许我们在每页显示特定数量的帖子,并导航到包含帖子的特定数量的页面。

默认情况下,GET 请求会检索每页 10 个帖子的集合。让我们看看如何提交 GET 请求来检索每页仅五个帖子:

$GET /wp/v2/posts?per_page=5

上述请求使用 per_page 变量,如果您使用过 WP_Query(),您可能会熟悉该变量。

page 参数与 per_page 参数结合使用,用于导航到特定数量的页面。每页检索到五个帖子后,我们将发出以下请求以导航到第二页:

$GET /wp/v2/posts?per_page=5&page=2

在使用 WP REST API 在列表页面上构建分页时,per_pagepage 过滤器非常方便。

除了上述请求返回的帖子集合之外,服务器还返回许多标头以及包含有用信息的响应,包括帖子总数和页数。这些值包含在 X-WP-TotalPagesX-WP-Total 响应标头中。

获取数据的WP REST API

使用 WP REST API 创建分页时,X-WP-TotalPagesX-WP-Total 响应标头非常有用,因为它们列出了页面总数以及帖子总数。

除了分页过滤器之外,您还可以按日期过滤帖子。

因此,如果我们要查找日期为 2015-10-15(yyyy/mm/dd)发布的帖子,可以通过以下查询来实现:

$ GET /wp/v2/posts?modified_after=2015-10-14&modified_before=2015-10-16

我们已经在本教程的上一节中了解了如何使用 categories 参数获取属于特定类别或多个类别的帖子。让我们看看如何显示属于 id 为 5 和 6 的类别的帖子:

$ GET /wp/v2/posts?categories=5,6

上述请求将检索属于 ID 为 5 和 6 的类别的所有帖子的列表。

通过以下方式使用 categories_exclude 参数可以达到相反的效果:

$ GET /wp/v2/posts?categories_exclude=5,6

这将检索帖子列表,同时排除属于 ID 为 5 或 6 的类别的所有帖子。

现在我们已经在 WP REST API 的帮助下查看了查询帖子时的不同选项,我们准备进一步推进我们的旅程并查看 WP REST API 支持的一些其他资源。

使用帖子修订、类别和标签

帖子修订提供了一种查看和恢复对帖子所做编辑的方法。 WP REST API 提供了一种通过查询 /posts/<id>/revisions</id> 端点来查看帖子的所有修订版本的方法。因此,对于 ID 为 10 的给定帖子,可以通过发送以下请求来检索所有修订:

$ GET /wp/v2/posts/10/revisions

上述请求将返回一个包含修订对象的数组。修订对象包含在发布对象中找到的属性的子集。下面是 Postman 中的修订对象示例:

获取数据的WP REST API

只要我们知道其 ID,就可以检索特定的修订版本。因此,可以通过以下对象检索 ID 为 10 的帖子上 ID 为 2 的修订:

$ GET /wp/v2/posts/10/revisions/2

上述请求将返回单个修订对象。

除了帖子修订之外,还可以通过以下请求检索特定帖子的类别:

$ GET /wp/v2/categories?post=<post_id>

对于标签,我们使用以下请求,其中 <post_id></post_id> 是帖子的 ID:

$ GET /wp/v2/tags?post=<post_id>

如果我们需要检索 ID 为 10 的帖子的帖子元数据,我们将以经过身份验证的用户身份发送以下请求:

$ GET /wp/v2/posts/10/meta

这将返回一个元对象数组。

请注意,要在 WP REST API 中使用帖子和页面元,您需要安装配套插件,该插件可从 WP REST API 团队在 GitHub 上获取。

使用其他资源

到目前为止,我们已经为使用 WP REST API 检索数据奠定了相当坚实的基础。我们已经研究了选项请求以及它如何帮助我们在不需要外部文档的情况下探索 API。

您始终可以向特定资源发送 OPTIONS 请求,并检查它支持哪些端点和参数。如果您需要列出 WP REST API 提供的所有路由,您可以向 /wp-json 处的索引端点发送 GET 请求,正如我们在本教程的开始。

考虑到自我文档的优势,我认为我们不需要进一步探索本教程中的每个单独资源,因为您现在可以自己完成此操作。

接下来会发生什么?

在这个冗长的教程中,我们学习了使用 OPTIONS 请求探索 API 并使用 WP REST API 从服务器检索数据。我们只查看了一些资源,包括帖子、修订后和帖子元,因为我们无法仅在一个教程中涵盖所有支持的资源。但您现在应该能够使用我们在本教程中介绍的技术自行探索 API。

WordPress 的经济非常活跃。有主题、插件、库和许多其他产品可以帮助您构建网站和项目。该平台的开源性质也使其成为提高编程技能的绝佳选择。

在本系列的下一部分中,我们将学习执行 CRUD 的其他三个操作,即创建、更新和删除资源。所以请继续关注。

The above is the detailed content of WP REST API to get data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn