[API] Một ví dụ về Biến đường dẫn (ok)

https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/

<?php
/**
 * This is our callback function to return our products.
 *
 * @param WP_REST_Request $request This function accepts a rest request to process data.
 */
function prefix_get_products($request) {
  // In practice this function would fetch the desired data. Here we are just making stuff up.
  $products = array(
    '1' => 'I am product 1',
    '2' => 'I am product 2',
    '3' => 'I am product 3',
  );
  return rest_ensure_response($products);
}
/**
 * This is our callback function to return a single product.
 *
 * @param WP_REST_Request $request This function accepts a rest request to process data.
 */
function prefix_get_product($request) {
  // In practice this function would fetch the desired data. Here we are just making stuff up.
  $products = array(
    '1' => 'I am product 1',
    '2' => 'I am product 2',
    '3' => 'I am product 3',
  );
  // Here we are grabbing the 'id' path variable from the $request object. WP_REST_Request implements ArrayAccess, which allows us to grab properties as though it is an array.
  $id = (string) $request['id'];
  if (isset($products[$id])) {
    // Grab the product.
    $product = $products[$id];
    // Return the product as a response.
    return rest_ensure_response($product);
  } else {
    // Return a WP_Error because the request product was not found. In this case we return a 404 because the main resource was not found.
    return new WP_Error('rest_product_invalid', esc_html__('The product does not exist.', 'my-text-domain'), array('status' => 404));
  }
  // If the code somehow executes to here something bad happened return a 500.
  return new WP_Error('rest_api_sad', esc_html__('Something went horribly wrong.', 'my-text-domain'), array('status' => 500));
}
/**
 * This function is where we register our routes for our example endpoint.
 */
function prefix_register_product_routes() {
  // Here we are registering our route for a collection of products.
  register_rest_route('my-shop/v1', '/products', array(
    // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
    'methods'  => WP_REST_Server::READABLE,
    // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
    'callback' => 'prefix_get_products',
  ));
  // Here we are registering our route for single products. The (?P<id>[\d]+) is our path variable for the ID, which, in this example, can only be some form of positive number.
  register_rest_route('my-shop/v1', '/products/(?P<id>[\d]+)', array(
    // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
    'methods'  => WP_REST_Server::READABLE,
    // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
    'callback' => 'prefix_get_product',
  ));
}
add_action('rest_api_init', 'prefix_register_product_routes');
?>

Ví dụ trên bao gồm rất nhiều. Phần quan trọng cần lưu ý là trong lộ trình thứ hai mà chúng ta đăng ký, chúng ta thêm vào một biến đường dẫn / (? P [ d] +) vào đường dẫn tài nguyên / sản phẩm của chúng ta. Biến đường dẫn là một biểu thức chính quy. Trong trường hợp này, nó sử dụng [ d] + để biểu thị rằng phải là bất kỳ ký tự số nào ít nhất một lần. Nếu bạn đang sử dụng ID số cho tài nguyên của mình thì đây là một ví dụ tuyệt vời về cách sử dụng biến đường dẫn. Khi sử dụng các biến đường dẫn, bây giờ chúng ta phải cẩn thận về những gì có thể được so khớp vì nó là đầu vào của người dùng.

May mắn thay, regex sẽ lọc ra bất cứ thứ gì không phải là số. Tuy nhiên, điều gì sẽ xảy ra nếu sản phẩm cho ID được yêu cầu không tồn tại. Chúng ta cần xử lý lỗi. Bạn có thể thấy cách cơ bản mà chúng tôi đang xử lý lỗi trong ví dụ mã ở trên. Khi bạn trả về một WP_Error trong lệnh gọi lại điểm cuối của mình, máy chủ API sẽ tự động xử lý việc gửi lỗi cho máy khách.

Mặc dù phần này là về các tuyến đường, chúng tôi đã đề cập khá kỹ về các điểm cuối. Các điểm cuối và các tuyến đường có mối quan hệ với nhau, nhưng chúng chắc chắn có sự khác biệt.

Last updated