用于获取数据的rest API

Wordpress7个月前发布 SUYEONE
880 0 0

In the previous segment of this Series. we delved into the concept of the WP REST API and how it empowers us to build better applications using the WordPress backend. We then explored two methods for setting up authentication on the server to generate authenticated requests: Basic Authentication, which is useful for rapid prototyping in development environments, and OAuth 2.0, recommended for production environments due to its increased Security.

Now that we understand authentication, we’re ready to make authenticated requests to unlock the full potential of the WP REST API. For the simplicity of this series, we’ll use Basic Authentication, but we advise using OAuth 2.0 (offered 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 authentication mechanisms to control access to API endpoints. It comes with various authentication methods, including Basic Authentication, API Key Authentication, JWT Authentication, and OAuth 2.0. After setting up authentication, you can define access control rules for different API endpoints, allowing you to configure which users or roles have permission to access specific endpoints. It also provides options to restrict access based on user roles, capabilities, or specific user IDs.

In this installment, we’ll embark on our first hands-on experience with the WP REST API. We’ll:

1. Examine the structure of a GET request and how an OPTIONS request describes itself.
2. Analyze the server’s response to a GET request, including properties, schema, and links.
3. Investigate the usage of OPTIONS requests to navigate the API, handle posts, revisions, categories, tags, and other resources.

Let’s start by analyzing a simple GET request.

GET Request Analysis
Before diving into the detAIls of retrieving Data with the WP REST API, we need to be familiar with the syntax of requests sent to the server. This foundation will serve us well in future interActions with the WP REST API.

Consider the following request sent to the server:

“`
$ GET https://localserver/WP-JSON/WP/V2/posts
“`

Here’s a breakdown of the request URI:

1. `https://localserver/`: The URL of your local development server; this could be any URL depending on where you’ve installed WordPress.
2. `/WP-JSON/`: The endpoint prefix for the WP REST API.
3. `/WP/`: The namespace for the WP REST API.
4. `/v2/`: The version of the WP REST API.
5. `/posts`: The resource we want to retrieve from the server.

To fetch a specific post, you can reference its ID like this:

“`
$ GET /wp/v2/posts/100
“`

This request would return the post object with an ID of 100.

In many cases, you might need to search for posts that meet certain criteria. For example, you can filter posts by category as shown below:

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

This request retrieves all posts belonging to categories with IDs 20 and 30. The `categories` parameter can accept one or more category IDs, returning posts assigned to those specific term IDs in the ‘category’ taxonomy.

This syntax is equivalent to the following `WP_Query()` call:

“`php
array(
array(
‘taxonomy’ => ‘category’,
‘field’ => ‘term_id’,
‘terms’ => array(20, 30),
),
),
));
“`

So, the GET request above will fetch a list of posts belonging to both categories with IDs 20 and 30. The same syntax applies to array parameters with more than two elements.

Now that we know how to format GET requests and provide their parameters, let’s explore OPTIONS requests.

OPTIONS Requests for Navigating the API
OPTIONS requests are invaluable for exploring the API. They act as a self-documenting means by listing all available HTTP methods and parameters on an endpoint, making the API more accessible.

Let’s send an OPTIONS request to the `/wp/v2/posts` route to check the supported endpoints and query data:

“`
$curl -X OPTIONS /wp/v2/posts
“`

Use your preferred tool, such as Postman, to send this request, ensuring the full path to your server is included.

The response will list all routes and their supported methods and parameters, eliminating the need for external documentation when performing CRUD operations on different resources.

Having reviewed the OPTIONS request for exploring the API, let’s proceed to retrieve data from the server using the WP REST API.

Handling Posts
We’ve now acquainted ourselves with OPTIONS requests, a self-documenting way to assess API availability and the methods and parameters it supports. With this knowledge, we can retrieve various resources from the server using the WP REST API.

We’ll start with posts since the WP REST API exposes some commonly used query variables directly through top-level parameters on GET endpoints. These parameters include:

– `context`: Defines the context of the request, with possible values being ‘view’, ’embed’, or ‘eDiT’. The default is ‘view’.
– `page`: The current page number for the post collection. The default is 1.
– `per_page`: The total number of posts per page. The default is 10.
– `search`: Limits results to those matching the specified string.
– `after`: Returns only posts published after the specified date.
– `modified_after`: Returns only posts modified after the specified date.
– `author`: Limits results to those belonging to a specific author by their ID.
– `author_exclude`: Excludes posts assigned to a particular author by their ID.
– `before`: Returns only posts published before the specified date.
– `modified_before`: Returns only posts modified before the specified date.
– `exclude`: Excludes posts by their ID array.
– `include`: Limits results to posts with the specified IDs.
– `offset`: Offsets the search results by a specified number.
– `order`: The order of the collection, either ‘asc’ or ‘desc’.
– `orderby`: The property to sort the collection by. Possible values include ‘author’, ‘date’, ‘ID’, ‘include’, ‘modified’, ‘parent’, ‘relevance’, ‘slug’, ‘include_slugs’, and ‘title’.
– `search_columns`: An array of column names to search within.
– `slug`: Limits results to posts with a specific slug.
– `status`: Filters the collection to posts with a specific status.
– `tax_query`: Filters the collection based on the relationship between multiple taxonomies.

Using the `embed` value for the `context` parameter retrieves a minimal subset of post attributes. Using the `edit` value requires authentication with a user having the `edit_posts` capability and provides fields like `title.rendered` and `content.raw`.

Other parameters are self-explanatory and can be utilized in your HTTP client.

These basic parameters allow you to query posts based on specific conditions. In addition to these standard parameters, the WP REST API also allows filtering records through various other criteria, enabling querying similar to the `WP_Query()` class.

Pagination parameters are crucial among these filters, widely used in lists of posts. They enable displaying a specific number of posts per page and navigating through pages containing posts. By default, a GET request retrieves a collection of 10 posts per page. Let’s see how to fetch five posts per page:

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

After fetching five posts per page, you can navigate to the second page with:

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

When building pagination with the WP REST API on a list page, the `per_page` and `page` filters come in handy.

The server response includes headers like `X-WP-TotalPages` and `X-WP-Total`, which list the total number of pages and posts, respectively. These headers are invaluable when creating pagination with the WP REST API.

In addition to these filters, you can also filter posts by date. To fetch posts published on October 15, 2015 (yyyy/mm/DD), you’d use:

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

As we learned earlier, the `categories` parameter can fetch posts belonging to specific categories. Here’s how to display posts belonging to categories with IDs 5 and 6:

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

To achieve the opposite effect, excluding posts from categories 5 and 6, use the `categories_exclude` parameter:

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

Now that we’ve explored various options for querying posts with the WP REST API, we’re ready to move forward and learn about other supported resources, including post revisions, categories, and tags.

Dealing with Post Revisions, Categories, and Tags
Post revisions offer a way to view and revert changes made to a post. The WP REST API allows querying revisions using the `/posts//revisions` endpoint:

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

This request returns an array of revision objects, each containing a subset of properties from the published object. Here’s an example of a revision object in Postman:

As long as you know the ID, you can fetch a specific revision, say revision #2 for post #10, with

© 版权声明

相关文章

暂无评论

暂无评论...
☺一键登录开启个人书签等功能!