/home/tip-luu-y-nho-khi-tao-wordpress-api-endpoint

TIP: Lưu ý nhỏ khi tạo WordPress API endpoint

Published on

Như các bạn đã biết thì từ bản 4.7 WordPress đã tích hợp API vào core.

Trong một dự án gần đây mình cần phải viết API, ban đầu mình viết như sau


add_action( 'rest_api_init', function () {
    register_rest_route( 'nhymxu', 'endpoint_get', ['method' => WP_REST_Server::READABLE, 'callback' => 'endpoint_get_callback'] );
} );

sau khi test thấy GET endpoint này ngon, mình bổ sung thêm 1 endpoint nữa

add_action( 'rest_api_init', function () {
    register_rest_route( 'nhymxu', 'endpoint_get', ['method' => WP_REST_Server::READABLE, 'callback' => 'endpoint_get_callback'] );
    register_rest_route( 'nhymxu', 'endpoint_all', ['method' => WP_REST_Server::ALLMETHODS, 'callback' => 'endpoint_all_callback'] );
} );

test GET request tiếp, ngon lành cành đào.

mở postman lên test thử POST request xem sao.

Ố ồ, đời không như là mơ. POST request gặp lỗi

{  
   "code": "rest_no_route",  
   "message": "No route was found matching the URL and request method", 
    "data":
     {
        "status": 404
     }

}

rõ ràng GET ngon mà, test lại GET, vẫn ngon.

Sau một hồi ngó lại document xem mình có code sai chỗ nào không thì thấy vẫn đúng.

Thế nào mình lại thử tách ra thành như này

add_action( 'rest_api_init', function () {
    register_rest_route( 'nhymxu', 'endpoint_get', ['method' => WP_REST_Server::READABLE, 'callback' => 'endpoint_get_callback'] );
} );
add_action( 'rest_api_init', function () {
    register_rest_route( 'nhymxu', 'endpoint_all', ['method' => WP_REST_Server::ALLMETHODS, 'callback' => 'endpoint_all_callback'] );
} );

test lại bằng Postman thấy chạy ngon lành các method luôn.

Chưa có thời gian chọc vào Core đọc xem vì sao nó lại thần kinh thế này. Cứ post tạm lên đây đã, bổ sung sau =))