# \[API] Một ví dụ sử dụng phương thức GET, POST cơ bản :) (ok)

![](/files/-MOAaZ4LgHqp2qjDR8ES)

![](/files/-MOAaaoszZV21SSSIY_k)

```
<?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_create_product($request) {
  // In practice this function would create a product. Here we are just making stuff up.
  return rest_ensure_response('Product has been created');
}
/**
 * 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 and creation of products.
  register_rest_route('my-shop/v1', '/products', array(
    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',
    ),
    array(
      // By using this constant we ensure that when the WP_REST_Server changes, our create endpoints will work as intended.
      'methods'  => WP_REST_Server::CREATABLE,
      // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
      'callback' => 'prefix_create_product',
    ),
  ));
}
add_action('rest_api_init', 'prefix_register_product_routes');
?>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/wordpress/api-mot-vi-du-su-dung-phuong-thuc-get-post-co-ban-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
