API là gì?

API là các phương thức, giao thức kết nối với các thư viện và ứng dụng khác. Nó là viết tắt của Application Programming Interface – giao diện lập trình ứng dụng. API cung cấp khả năng cung cấp khả năng truy xuất đến một tập các hàm hay dùng. Và từ đó có thể trao đổi dữ liệu giữa các ứng dụng.

REST API là gì?

REST API là một tiêu chuẩn dùng trong việc thiết kế API cho các ứng dụng web (thiết kế Web services) để tiện cho việc quản lý các resource. Nó chú trọng vào tài nguyên hệ thống (tệp văn bản, ảnh, âm thanh, video, hoặc dữ liệu động…), bao gồm các trạng thái tài nguyên được định dạng và được truyền tải qua HTTP.

Register GET Route

Static Route

add_action( 'rest_api_init', function() {
  register_rest_route( 'my/v1', '/projects', [
    'methods' => 'GET',
    'callback' => 'get_projects',
    'permission_callback' => '__return_true',
  ] );
} );

// Get all projects and assign thumbnail
function get_projects( $params ) {
  $projects =  get_posts( [
    'post_type' => 'project',
    'posts_per_page' => 10
  ] );

  foreach( $projects as &$p ) {
    $p->thumbnail = get_the_post_thumbnail_url( $p->ID );
  }

  return $projects;
}

Đoạn mã trên sẽ tạo một điểm cuối tại https://yoursite.com/wp-json/my/v1/projects .

Bạn có thể tự hỏi là gì my/v1. Đó là namespace và version .

Không gian tên là để xác định một nhóm. Bạn có thể sử dụng bất cứ thứ gì, nhưng hãy cố gắng giữ cho nó ngắn gọn.

Phiên bản là để phân biệt một tuyến đường được cập nhật. Khi một ngày nào đó bạn muốn cập nhật API này, bạn nên giữ nguyên trạng thái cũ v1và v2thay vào đó tạo một tuyến mới . Điều này là để ngăn các ứng dụng hiện có đang sử dụng v1 bị hỏng.

Dynamic Route at /project/[id] to get a specific project:

add_action( 'rest_api_init', function() {
  register_rest_route( 'my/v1', '/project/(?P<id>\d+)', [
    'methods' => 'GET',
    'callback' => 'get_project',
    'permission_callback' => '__return_true',
  ] );
} );

// Get single project
function get_project( $params ) {
  $project = get_post( $params['id'] );
  $project->thumbnail = get_the_post_thumbnail_url( $project->ID );
  return $project;
}

Register POST Route

add_action( 'rest_api_init', function() {
  register_rest_route( 'my/v1', '/projects_search', [
    'methods' => 'POST',
    'callback' => 'post_projects_search',
    'permission_callback' => '__return_true',
  ] );
} );

// Search projects
function post_projects_search( $request ) {
  // Get sent data and set default value
  $params = wp_parse_args( $request->get_params(), [
    'title' => '',
    'category' => null
  ] );

  $args = [
    'post_type' => 'project',
    's' => $params['title'],
  ];

  if( $params['category'] ) {
    $args['tax_query'] = [[
      'taxonomy' => 'project_category',
      'field' => 'id',
      'terms' => $params['category']
    ]];
  }

  return get_posts( $args );
}

Test API sử dụng Postman

Đóng gói API sử dụng class

Nếu các API có liên quan với nhau bạn nên đặt chúng vào một class. Nó không chỉ gọn gàng hơn, mà còn giúp bạn tránh được các lỗi trùng lặp tên hàm.

if( !class_exists( 'MyAPI' ) ) {

class MyAPI {
  function __construct() {
    add_action( 'rest_api_init', [$this, 'init'] );
  }

  function init() {
    register_rest_route( 'my/v1', '/projects', [
      'methods' => 'GET',
      'callback' => [$this, 'get_projects'],
    ] );

    register_rest_route( 'my/v1', '/project/(?P<id>\d+)', [
      'methods' => 'GET',
      'callback' => [$this, 'get_project'],
    ] );

    register_rest_route( 'my/v1', '/projects_search', [
      'methods' => 'POST',
      'callback' => [$this, 'post_projects_search']
    ] );
  }

  // Get recent projects
  function get_projects( $params ) {
    $projects =  get_posts( [
      'post_type' => 'project',
      'posts_per_page' => 10
    ] );

    foreach( $projects as &$p ) {
      $p->thumbnail = get_the_post_thumbnail_url( $p->ID );
    }

    return $projects;
  }

  // Get single project
  function get_project( $params ) {
    $project = get_post( $params['id'] );
    $project->thumbnail = get_the_post_thumbnail_url( $project->ID );
    return $project;
  }

  // Search projects
  function post_projects_search( $request ) {
    // Get sent data and set default value
    $params = wp_parse_args( $request->get_params(), [
      'title' => '',
      'category' => null
    ] );

    $args = [
      'post_type' => 'project',
      's' => $params['title'],
    ];

    if( $params['category'] ) {
      $args['tax_query'] = [[
        'taxonomy' => 'project_category',
        'field' => 'id',
        'terms' => $params['category']
      ]];
    }

    return get_posts( $args );
  }
}

new MyAPI();
}

How to Make Custom REST API (Beginner’s Guide)

Bài viết liên quan

post-no-image

Chia sẻ một số thư viện loading css đẹp

giai-phap-chinh-css-khong-bi-luu-cache-trinh-duyet

Giải pháp tốt khi chỉnh sửa css mà không sợ bị lưu cache trình duyệt

post-no-image

Một số css tùy biến thẻ input type: select, number

post-no-image

Tắt lazyload cho một số hình ảnh

post-no-image

Tuỳ biến layout YITH WooCommerce Wishlist

post-no-image

Một số hook hoặc filter thường sử dụng trong plugin WPML