Why is my custom API endpoint not working?2019 Community Moderator Election Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Moderator Election Q&A - QuestionnaireWordpress Api Get DraftsSending post data over REST API, how to parse shortcodes in post_content?How to call wp plugin REST functions without curl?How to use Wordpress rest API with Angularjs 4Update CPT meta data using REST APIcustom REST endpoint not passing body of POST request to callbackCustom Rest API namespace and endpoints are responding with 404 & 503 errorsHow to get custom fields in a post when publishedHow to feed a HTML5's EventSource with a REST API custom endpoint?Callback to custom field is not working in Wordpress REST API

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

What is this single-engine low-wing propeller plane?

Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

Disable hyphenation for an entire paragraph

What would be the ideal power source for a cybernetic eye?

Dominant seventh chord in the major scale contains diminished triad of the seventh?

How to deal with a team lead who never gives me credit?

Single word antonym of "flightless"

Right-skewed distribution with mean equals to mode?

Using et al. for a last / senior author rather than for a first author

Can a non-EU citizen traveling with me come with me through the EU passport line?

Why is "Consequences inflicted." not a sentence?

Should I call the interviewer directly, if HR aren't responding?

Diagram with tikz

"Seemed to had" is it correct?

Why is black pepper both grey and black?

What LEGO pieces have "real-world" functionality?

I am not a queen, who am I?

What do you call a phrase that's not an idiom yet?

Does surprise arrest existing movement?

I need to find the potential function of a vector field.

Do you forfeit tax refunds/credits if you aren't required to and don't file by April 15?

Models of set theory where not every set can be linearly ordered

What causes the vertical darker bands in my photo?



Why is my custom API endpoint not working?



2019 Community Moderator Election
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Moderator Election Q&A - QuestionnaireWordpress Api Get DraftsSending post data over REST API, how to parse shortcodes in post_content?How to call wp plugin REST functions without curl?How to use Wordpress rest API with Angularjs 4Update CPT meta data using REST APIcustom REST endpoint not passing body of POST request to callbackCustom Rest API namespace and endpoints are responding with 404 & 503 errorsHow to get custom fields in a post when publishedHow to feed a HTML5's EventSource with a REST API custom endpoint?Callback to custom field is not working in Wordpress REST API



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















I tried to include this code in my plug-in php files as well as in functions.php.
(In the end I would like it to be in the plug-in's php file but I'm not yet sure if possible, that would probably be the topic of another question.)



It is a very basic method for now, I'm just trying to get a response with some content.



In both cases, I get a 404 response.



add_action( 'rest_api_init', function () 
register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(
'methods' => 'GET, POST',
'callback' => 'api_method',
) );
);

function api_method($data)
var_dump($data);
return 'API method end.';



And I tried to access URLs (in brower or with AJAX)



  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get/

I guess I'm missing something.










share|improve this question







New contributor




TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Rest API endpoints live at /wp-json, to include plugin_dir_url in your endpoint registration is extremely unusual, I would strongly recommend against REST endpoint URLs in the plugins folder ( mostly because that's not how the API works, you can't have those kinds of URLs )

    – Tom J Nowell
    Apr 10 at 15:07











  • @TomJNowell – Can you see why this question got so many views in such a short time? Should I ask this on Meta?

    – leymannx
    Apr 10 at 21:40











  • asking on meta is a good idea, I'm not sure how we can see views though. Maybe your question was well written and popular? :)

    – Tom J Nowell
    Apr 11 at 9:20

















4















I tried to include this code in my plug-in php files as well as in functions.php.
(In the end I would like it to be in the plug-in's php file but I'm not yet sure if possible, that would probably be the topic of another question.)



It is a very basic method for now, I'm just trying to get a response with some content.



In both cases, I get a 404 response.



add_action( 'rest_api_init', function () 
register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(
'methods' => 'GET, POST',
'callback' => 'api_method',
) );
);

function api_method($data)
var_dump($data);
return 'API method end.';



And I tried to access URLs (in brower or with AJAX)



  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get/

I guess I'm missing something.










share|improve this question







New contributor




TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Rest API endpoints live at /wp-json, to include plugin_dir_url in your endpoint registration is extremely unusual, I would strongly recommend against REST endpoint URLs in the plugins folder ( mostly because that's not how the API works, you can't have those kinds of URLs )

    – Tom J Nowell
    Apr 10 at 15:07











  • @TomJNowell – Can you see why this question got so many views in such a short time? Should I ask this on Meta?

    – leymannx
    Apr 10 at 21:40











  • asking on meta is a good idea, I'm not sure how we can see views though. Maybe your question was well written and popular? :)

    – Tom J Nowell
    Apr 11 at 9:20













4












4








4








I tried to include this code in my plug-in php files as well as in functions.php.
(In the end I would like it to be in the plug-in's php file but I'm not yet sure if possible, that would probably be the topic of another question.)



It is a very basic method for now, I'm just trying to get a response with some content.



In both cases, I get a 404 response.



add_action( 'rest_api_init', function () 
register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(
'methods' => 'GET, POST',
'callback' => 'api_method',
) );
);

function api_method($data)
var_dump($data);
return 'API method end.';



And I tried to access URLs (in brower or with AJAX)



  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get/

I guess I'm missing something.










share|improve this question







New contributor




TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I tried to include this code in my plug-in php files as well as in functions.php.
(In the end I would like it to be in the plug-in's php file but I'm not yet sure if possible, that would probably be the topic of another question.)



It is a very basic method for now, I'm just trying to get a response with some content.



In both cases, I get a 404 response.



add_action( 'rest_api_init', function () 
register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(
'methods' => 'GET, POST',
'callback' => 'api_method',
) );
);

function api_method($data)
var_dump($data);
return 'API method end.';



And I tried to access URLs (in brower or with AJAX)



  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get

  • http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get/

I guess I'm missing something.







rest-api endpoints






share|improve this question







New contributor




TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Apr 10 at 14:30









TTTTTT

1658




1658




New contributor




TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






TTT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • Rest API endpoints live at /wp-json, to include plugin_dir_url in your endpoint registration is extremely unusual, I would strongly recommend against REST endpoint URLs in the plugins folder ( mostly because that's not how the API works, you can't have those kinds of URLs )

    – Tom J Nowell
    Apr 10 at 15:07











  • @TomJNowell – Can you see why this question got so many views in such a short time? Should I ask this on Meta?

    – leymannx
    Apr 10 at 21:40











  • asking on meta is a good idea, I'm not sure how we can see views though. Maybe your question was well written and popular? :)

    – Tom J Nowell
    Apr 11 at 9:20

















  • Rest API endpoints live at /wp-json, to include plugin_dir_url in your endpoint registration is extremely unusual, I would strongly recommend against REST endpoint URLs in the plugins folder ( mostly because that's not how the API works, you can't have those kinds of URLs )

    – Tom J Nowell
    Apr 10 at 15:07











  • @TomJNowell – Can you see why this question got so many views in such a short time? Should I ask this on Meta?

    – leymannx
    Apr 10 at 21:40











  • asking on meta is a good idea, I'm not sure how we can see views though. Maybe your question was well written and popular? :)

    – Tom J Nowell
    Apr 11 at 9:20
















Rest API endpoints live at /wp-json, to include plugin_dir_url in your endpoint registration is extremely unusual, I would strongly recommend against REST endpoint URLs in the plugins folder ( mostly because that's not how the API works, you can't have those kinds of URLs )

– Tom J Nowell
Apr 10 at 15:07





Rest API endpoints live at /wp-json, to include plugin_dir_url in your endpoint registration is extremely unusual, I would strongly recommend against REST endpoint URLs in the plugins folder ( mostly because that's not how the API works, you can't have those kinds of URLs )

– Tom J Nowell
Apr 10 at 15:07













@TomJNowell – Can you see why this question got so many views in such a short time? Should I ask this on Meta?

– leymannx
Apr 10 at 21:40





@TomJNowell – Can you see why this question got so many views in such a short time? Should I ask this on Meta?

– leymannx
Apr 10 at 21:40













asking on meta is a good idea, I'm not sure how we can see views though. Maybe your question was well written and popular? :)

– Tom J Nowell
Apr 11 at 9:20





asking on meta is a good idea, I'm not sure how we can see views though. Maybe your question was well written and popular? :)

– Tom J Nowell
Apr 11 at 9:20










2 Answers
2






active

oldest

votes


















2














Maybe start with just GET. Your route looks weird as well. Try just:



register_rest_route('my-project/v1', '/action/', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'api_method',
]);



And your callback is not returning a valid response. Let your callback look more like this:



$data = [ 'foo' => 'bar' ];

$response = new WP_REST_Response($data, 200);

// Set headers.
$response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);

return $response;



Finally you must combine wp-json, the namespace my-project/v1 and your route action to the URL you now can check for what you get:




https://my-domain.local/wp-json/my-project/v1/action





share|improve this answer

























  • I just followed what you suggested, tried my-domain.local/my-project/v1 , my-domain.local/my-project/v1/get (with and without trailing slashes), still getting 404 response. At the moment, the code is in functions.php.

    – TTT
    Apr 10 at 15:02











  • @TTT – It must be my-domain.local/wp-json/my-project/v1/action as you've specified /action/ to be your route.

    – leymannx
    Apr 10 at 15:12






  • 1





    Thank you, this worked. Well since the answer is in the comment, I not sure if I should check the answer as solution right away. Also, I can make this return something else than JSON, right ? (I mean not like XML, like php processed HTML code.) ... Then the URL would still contain "wp-json". Weird ... or is there another type of API?

    – TTT
    Apr 10 at 15:17






  • 2





    @TTT you can store HTML in JSON as a string then JSON decode in the browser

    – Tom J Nowell
    Apr 10 at 15:20






  • 1





    I just found and tested this way here that looks cleaned than including HTML in JSON: gist.github.com/petenelson/6dc1a405a6e7627b4834

    – TTT
    Apr 10 at 16:01


















3














Here's your problem:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Specifically the idea that this is possible:



http://my-domain.local/wp-content/plugins/my-project/api/v1/form


This is extremely unusual, and runs counter to what's in the docs, handbook, and tutorials.



REST API endpoints live at the REST API, which lives at the URL returned by rest_url(). They live at yoursite.com/wp-json. An endpoint is not a full URL path, or an independent API disconnected from the main API.



Instead, you need to define your endpoint names in terms of namespaces and endpoints, and visit the correct URL as described in the REST API's discovery mechanisms.



If we use this:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Then we would expect this:



example.com/wp-json/wp-content/plugins/my-project/api/v1/form/action



That URL is quite long, and has a number of problems:



  • The first parameter is a namespace, not a URL

  • it's not possible to correctly separate out v1 of the API from v2 due to the way that that /form component has been put in the first parameter, not the second. The first parameter is a namespace, the second a route


  • /action is /action, it doesn't get swapped out for GET OR POST

There are also problems with the callback function:



function api_method($data) {
var_dump($data);


An endpoint needs to return its data, it cannot output it directly as var_dump would, otherwise the returned data is invalid JSON.



Finally, the methods parameter is incorrect:



'methods' => 'GET, POST',


methods doesn't take a comma separated list, no docs suggest doing this either. Instead, use the predefined values provided by the REST API such as WP_REST_Server::READABLE or WP_REST_Server::ALLMETHODS, these are all mentioned in the handbook and the official documentation for register_rest_route.



A better route to register would be:



 register_rest_route( 'my-project/form/v1', '/action', array(


Giving us:



example.com/wp-json/my-project/form/v1/action



Notice how I removed the plugin URL and the redundant /api fragment ( it's obvious it's an API already )






share|improve this answer




















  • 1





    Thank you for detailed explanation. I've already marked an answer that came quicker as solution however.

    – TTT
    Apr 10 at 15:25











  • You can change your mind about which answer is best, but eitherway think of the site as a wiki, there can be more than 1 good answer

    – Tom J Nowell
    Apr 10 at 17:21











  • One reason why I don't want to change answer is that I have conretely tested and applied the answer I selected as solution. Your answer brought more details and things I had thought in a wrong way somehow, but I haven't litteraly tested and checked it all. I also think that on most StackExchange sites, first good answers get selected, next one get votes. And though this has me scratching my head a bit, I see no reason to remove the solution rewards from the person who solved it first.

    – TTT
    Apr 10 at 17:42











Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "110"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






TTT is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fwordpress.stackexchange.com%2fquestions%2f333999%2fwhy-is-my-custom-api-endpoint-not-working%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Maybe start with just GET. Your route looks weird as well. Try just:



register_rest_route('my-project/v1', '/action/', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'api_method',
]);



And your callback is not returning a valid response. Let your callback look more like this:



$data = [ 'foo' => 'bar' ];

$response = new WP_REST_Response($data, 200);

// Set headers.
$response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);

return $response;



Finally you must combine wp-json, the namespace my-project/v1 and your route action to the URL you now can check for what you get:




https://my-domain.local/wp-json/my-project/v1/action





share|improve this answer

























  • I just followed what you suggested, tried my-domain.local/my-project/v1 , my-domain.local/my-project/v1/get (with and without trailing slashes), still getting 404 response. At the moment, the code is in functions.php.

    – TTT
    Apr 10 at 15:02











  • @TTT – It must be my-domain.local/wp-json/my-project/v1/action as you've specified /action/ to be your route.

    – leymannx
    Apr 10 at 15:12






  • 1





    Thank you, this worked. Well since the answer is in the comment, I not sure if I should check the answer as solution right away. Also, I can make this return something else than JSON, right ? (I mean not like XML, like php processed HTML code.) ... Then the URL would still contain "wp-json". Weird ... or is there another type of API?

    – TTT
    Apr 10 at 15:17






  • 2





    @TTT you can store HTML in JSON as a string then JSON decode in the browser

    – Tom J Nowell
    Apr 10 at 15:20






  • 1





    I just found and tested this way here that looks cleaned than including HTML in JSON: gist.github.com/petenelson/6dc1a405a6e7627b4834

    – TTT
    Apr 10 at 16:01















2














Maybe start with just GET. Your route looks weird as well. Try just:



register_rest_route('my-project/v1', '/action/', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'api_method',
]);



And your callback is not returning a valid response. Let your callback look more like this:



$data = [ 'foo' => 'bar' ];

$response = new WP_REST_Response($data, 200);

// Set headers.
$response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);

return $response;



Finally you must combine wp-json, the namespace my-project/v1 and your route action to the URL you now can check for what you get:




https://my-domain.local/wp-json/my-project/v1/action





share|improve this answer

























  • I just followed what you suggested, tried my-domain.local/my-project/v1 , my-domain.local/my-project/v1/get (with and without trailing slashes), still getting 404 response. At the moment, the code is in functions.php.

    – TTT
    Apr 10 at 15:02











  • @TTT – It must be my-domain.local/wp-json/my-project/v1/action as you've specified /action/ to be your route.

    – leymannx
    Apr 10 at 15:12






  • 1





    Thank you, this worked. Well since the answer is in the comment, I not sure if I should check the answer as solution right away. Also, I can make this return something else than JSON, right ? (I mean not like XML, like php processed HTML code.) ... Then the URL would still contain "wp-json". Weird ... or is there another type of API?

    – TTT
    Apr 10 at 15:17






  • 2





    @TTT you can store HTML in JSON as a string then JSON decode in the browser

    – Tom J Nowell
    Apr 10 at 15:20






  • 1





    I just found and tested this way here that looks cleaned than including HTML in JSON: gist.github.com/petenelson/6dc1a405a6e7627b4834

    – TTT
    Apr 10 at 16:01













2












2








2







Maybe start with just GET. Your route looks weird as well. Try just:



register_rest_route('my-project/v1', '/action/', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'api_method',
]);



And your callback is not returning a valid response. Let your callback look more like this:



$data = [ 'foo' => 'bar' ];

$response = new WP_REST_Response($data, 200);

// Set headers.
$response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);

return $response;



Finally you must combine wp-json, the namespace my-project/v1 and your route action to the URL you now can check for what you get:




https://my-domain.local/wp-json/my-project/v1/action





share|improve this answer















Maybe start with just GET. Your route looks weird as well. Try just:



register_rest_route('my-project/v1', '/action/', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'api_method',
]);



And your callback is not returning a valid response. Let your callback look more like this:



$data = [ 'foo' => 'bar' ];

$response = new WP_REST_Response($data, 200);

// Set headers.
$response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);

return $response;



Finally you must combine wp-json, the namespace my-project/v1 and your route action to the URL you now can check for what you get:




https://my-domain.local/wp-json/my-project/v1/action






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 10 at 17:30

























answered Apr 10 at 14:36









leymannxleymannx

95111122




95111122












  • I just followed what you suggested, tried my-domain.local/my-project/v1 , my-domain.local/my-project/v1/get (with and without trailing slashes), still getting 404 response. At the moment, the code is in functions.php.

    – TTT
    Apr 10 at 15:02











  • @TTT – It must be my-domain.local/wp-json/my-project/v1/action as you've specified /action/ to be your route.

    – leymannx
    Apr 10 at 15:12






  • 1





    Thank you, this worked. Well since the answer is in the comment, I not sure if I should check the answer as solution right away. Also, I can make this return something else than JSON, right ? (I mean not like XML, like php processed HTML code.) ... Then the URL would still contain "wp-json". Weird ... or is there another type of API?

    – TTT
    Apr 10 at 15:17






  • 2





    @TTT you can store HTML in JSON as a string then JSON decode in the browser

    – Tom J Nowell
    Apr 10 at 15:20






  • 1





    I just found and tested this way here that looks cleaned than including HTML in JSON: gist.github.com/petenelson/6dc1a405a6e7627b4834

    – TTT
    Apr 10 at 16:01

















  • I just followed what you suggested, tried my-domain.local/my-project/v1 , my-domain.local/my-project/v1/get (with and without trailing slashes), still getting 404 response. At the moment, the code is in functions.php.

    – TTT
    Apr 10 at 15:02











  • @TTT – It must be my-domain.local/wp-json/my-project/v1/action as you've specified /action/ to be your route.

    – leymannx
    Apr 10 at 15:12






  • 1





    Thank you, this worked. Well since the answer is in the comment, I not sure if I should check the answer as solution right away. Also, I can make this return something else than JSON, right ? (I mean not like XML, like php processed HTML code.) ... Then the URL would still contain "wp-json". Weird ... or is there another type of API?

    – TTT
    Apr 10 at 15:17






  • 2





    @TTT you can store HTML in JSON as a string then JSON decode in the browser

    – Tom J Nowell
    Apr 10 at 15:20






  • 1





    I just found and tested this way here that looks cleaned than including HTML in JSON: gist.github.com/petenelson/6dc1a405a6e7627b4834

    – TTT
    Apr 10 at 16:01
















I just followed what you suggested, tried my-domain.local/my-project/v1 , my-domain.local/my-project/v1/get (with and without trailing slashes), still getting 404 response. At the moment, the code is in functions.php.

– TTT
Apr 10 at 15:02





I just followed what you suggested, tried my-domain.local/my-project/v1 , my-domain.local/my-project/v1/get (with and without trailing slashes), still getting 404 response. At the moment, the code is in functions.php.

– TTT
Apr 10 at 15:02













@TTT – It must be my-domain.local/wp-json/my-project/v1/action as you've specified /action/ to be your route.

– leymannx
Apr 10 at 15:12





@TTT – It must be my-domain.local/wp-json/my-project/v1/action as you've specified /action/ to be your route.

– leymannx
Apr 10 at 15:12




1




1





Thank you, this worked. Well since the answer is in the comment, I not sure if I should check the answer as solution right away. Also, I can make this return something else than JSON, right ? (I mean not like XML, like php processed HTML code.) ... Then the URL would still contain "wp-json". Weird ... or is there another type of API?

– TTT
Apr 10 at 15:17





Thank you, this worked. Well since the answer is in the comment, I not sure if I should check the answer as solution right away. Also, I can make this return something else than JSON, right ? (I mean not like XML, like php processed HTML code.) ... Then the URL would still contain "wp-json". Weird ... or is there another type of API?

– TTT
Apr 10 at 15:17




2




2





@TTT you can store HTML in JSON as a string then JSON decode in the browser

– Tom J Nowell
Apr 10 at 15:20





@TTT you can store HTML in JSON as a string then JSON decode in the browser

– Tom J Nowell
Apr 10 at 15:20




1




1





I just found and tested this way here that looks cleaned than including HTML in JSON: gist.github.com/petenelson/6dc1a405a6e7627b4834

– TTT
Apr 10 at 16:01





I just found and tested this way here that looks cleaned than including HTML in JSON: gist.github.com/petenelson/6dc1a405a6e7627b4834

– TTT
Apr 10 at 16:01













3














Here's your problem:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Specifically the idea that this is possible:



http://my-domain.local/wp-content/plugins/my-project/api/v1/form


This is extremely unusual, and runs counter to what's in the docs, handbook, and tutorials.



REST API endpoints live at the REST API, which lives at the URL returned by rest_url(). They live at yoursite.com/wp-json. An endpoint is not a full URL path, or an independent API disconnected from the main API.



Instead, you need to define your endpoint names in terms of namespaces and endpoints, and visit the correct URL as described in the REST API's discovery mechanisms.



If we use this:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Then we would expect this:



example.com/wp-json/wp-content/plugins/my-project/api/v1/form/action



That URL is quite long, and has a number of problems:



  • The first parameter is a namespace, not a URL

  • it's not possible to correctly separate out v1 of the API from v2 due to the way that that /form component has been put in the first parameter, not the second. The first parameter is a namespace, the second a route


  • /action is /action, it doesn't get swapped out for GET OR POST

There are also problems with the callback function:



function api_method($data) {
var_dump($data);


An endpoint needs to return its data, it cannot output it directly as var_dump would, otherwise the returned data is invalid JSON.



Finally, the methods parameter is incorrect:



'methods' => 'GET, POST',


methods doesn't take a comma separated list, no docs suggest doing this either. Instead, use the predefined values provided by the REST API such as WP_REST_Server::READABLE or WP_REST_Server::ALLMETHODS, these are all mentioned in the handbook and the official documentation for register_rest_route.



A better route to register would be:



 register_rest_route( 'my-project/form/v1', '/action', array(


Giving us:



example.com/wp-json/my-project/form/v1/action



Notice how I removed the plugin URL and the redundant /api fragment ( it's obvious it's an API already )






share|improve this answer




















  • 1





    Thank you for detailed explanation. I've already marked an answer that came quicker as solution however.

    – TTT
    Apr 10 at 15:25











  • You can change your mind about which answer is best, but eitherway think of the site as a wiki, there can be more than 1 good answer

    – Tom J Nowell
    Apr 10 at 17:21











  • One reason why I don't want to change answer is that I have conretely tested and applied the answer I selected as solution. Your answer brought more details and things I had thought in a wrong way somehow, but I haven't litteraly tested and checked it all. I also think that on most StackExchange sites, first good answers get selected, next one get votes. And though this has me scratching my head a bit, I see no reason to remove the solution rewards from the person who solved it first.

    – TTT
    Apr 10 at 17:42















3














Here's your problem:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Specifically the idea that this is possible:



http://my-domain.local/wp-content/plugins/my-project/api/v1/form


This is extremely unusual, and runs counter to what's in the docs, handbook, and tutorials.



REST API endpoints live at the REST API, which lives at the URL returned by rest_url(). They live at yoursite.com/wp-json. An endpoint is not a full URL path, or an independent API disconnected from the main API.



Instead, you need to define your endpoint names in terms of namespaces and endpoints, and visit the correct URL as described in the REST API's discovery mechanisms.



If we use this:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Then we would expect this:



example.com/wp-json/wp-content/plugins/my-project/api/v1/form/action



That URL is quite long, and has a number of problems:



  • The first parameter is a namespace, not a URL

  • it's not possible to correctly separate out v1 of the API from v2 due to the way that that /form component has been put in the first parameter, not the second. The first parameter is a namespace, the second a route


  • /action is /action, it doesn't get swapped out for GET OR POST

There are also problems with the callback function:



function api_method($data) {
var_dump($data);


An endpoint needs to return its data, it cannot output it directly as var_dump would, otherwise the returned data is invalid JSON.



Finally, the methods parameter is incorrect:



'methods' => 'GET, POST',


methods doesn't take a comma separated list, no docs suggest doing this either. Instead, use the predefined values provided by the REST API such as WP_REST_Server::READABLE or WP_REST_Server::ALLMETHODS, these are all mentioned in the handbook and the official documentation for register_rest_route.



A better route to register would be:



 register_rest_route( 'my-project/form/v1', '/action', array(


Giving us:



example.com/wp-json/my-project/form/v1/action



Notice how I removed the plugin URL and the redundant /api fragment ( it's obvious it's an API already )






share|improve this answer




















  • 1





    Thank you for detailed explanation. I've already marked an answer that came quicker as solution however.

    – TTT
    Apr 10 at 15:25











  • You can change your mind about which answer is best, but eitherway think of the site as a wiki, there can be more than 1 good answer

    – Tom J Nowell
    Apr 10 at 17:21











  • One reason why I don't want to change answer is that I have conretely tested and applied the answer I selected as solution. Your answer brought more details and things I had thought in a wrong way somehow, but I haven't litteraly tested and checked it all. I also think that on most StackExchange sites, first good answers get selected, next one get votes. And though this has me scratching my head a bit, I see no reason to remove the solution rewards from the person who solved it first.

    – TTT
    Apr 10 at 17:42













3












3








3







Here's your problem:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Specifically the idea that this is possible:



http://my-domain.local/wp-content/plugins/my-project/api/v1/form


This is extremely unusual, and runs counter to what's in the docs, handbook, and tutorials.



REST API endpoints live at the REST API, which lives at the URL returned by rest_url(). They live at yoursite.com/wp-json. An endpoint is not a full URL path, or an independent API disconnected from the main API.



Instead, you need to define your endpoint names in terms of namespaces and endpoints, and visit the correct URL as described in the REST API's discovery mechanisms.



If we use this:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Then we would expect this:



example.com/wp-json/wp-content/plugins/my-project/api/v1/form/action



That URL is quite long, and has a number of problems:



  • The first parameter is a namespace, not a URL

  • it's not possible to correctly separate out v1 of the API from v2 due to the way that that /form component has been put in the first parameter, not the second. The first parameter is a namespace, the second a route


  • /action is /action, it doesn't get swapped out for GET OR POST

There are also problems with the callback function:



function api_method($data) {
var_dump($data);


An endpoint needs to return its data, it cannot output it directly as var_dump would, otherwise the returned data is invalid JSON.



Finally, the methods parameter is incorrect:



'methods' => 'GET, POST',


methods doesn't take a comma separated list, no docs suggest doing this either. Instead, use the predefined values provided by the REST API such as WP_REST_Server::READABLE or WP_REST_Server::ALLMETHODS, these are all mentioned in the handbook and the official documentation for register_rest_route.



A better route to register would be:



 register_rest_route( 'my-project/form/v1', '/action', array(


Giving us:



example.com/wp-json/my-project/form/v1/action



Notice how I removed the plugin URL and the redundant /api fragment ( it's obvious it's an API already )






share|improve this answer















Here's your problem:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Specifically the idea that this is possible:



http://my-domain.local/wp-content/plugins/my-project/api/v1/form


This is extremely unusual, and runs counter to what's in the docs, handbook, and tutorials.



REST API endpoints live at the REST API, which lives at the URL returned by rest_url(). They live at yoursite.com/wp-json. An endpoint is not a full URL path, or an independent API disconnected from the main API.



Instead, you need to define your endpoint names in terms of namespaces and endpoints, and visit the correct URL as described in the REST API's discovery mechanisms.



If we use this:



register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(


Then we would expect this:



example.com/wp-json/wp-content/plugins/my-project/api/v1/form/action



That URL is quite long, and has a number of problems:



  • The first parameter is a namespace, not a URL

  • it's not possible to correctly separate out v1 of the API from v2 due to the way that that /form component has been put in the first parameter, not the second. The first parameter is a namespace, the second a route


  • /action is /action, it doesn't get swapped out for GET OR POST

There are also problems with the callback function:



function api_method($data) {
var_dump($data);


An endpoint needs to return its data, it cannot output it directly as var_dump would, otherwise the returned data is invalid JSON.



Finally, the methods parameter is incorrect:



'methods' => 'GET, POST',


methods doesn't take a comma separated list, no docs suggest doing this either. Instead, use the predefined values provided by the REST API such as WP_REST_Server::READABLE or WP_REST_Server::ALLMETHODS, these are all mentioned in the handbook and the official documentation for register_rest_route.



A better route to register would be:



 register_rest_route( 'my-project/form/v1', '/action', array(


Giving us:



example.com/wp-json/my-project/form/v1/action



Notice how I removed the plugin URL and the redundant /api fragment ( it's obvious it's an API already )







share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 10 at 17:22

























answered Apr 10 at 15:19









Tom J NowellTom J Nowell

33.3k44899




33.3k44899







  • 1





    Thank you for detailed explanation. I've already marked an answer that came quicker as solution however.

    – TTT
    Apr 10 at 15:25











  • You can change your mind about which answer is best, but eitherway think of the site as a wiki, there can be more than 1 good answer

    – Tom J Nowell
    Apr 10 at 17:21











  • One reason why I don't want to change answer is that I have conretely tested and applied the answer I selected as solution. Your answer brought more details and things I had thought in a wrong way somehow, but I haven't litteraly tested and checked it all. I also think that on most StackExchange sites, first good answers get selected, next one get votes. And though this has me scratching my head a bit, I see no reason to remove the solution rewards from the person who solved it first.

    – TTT
    Apr 10 at 17:42












  • 1





    Thank you for detailed explanation. I've already marked an answer that came quicker as solution however.

    – TTT
    Apr 10 at 15:25











  • You can change your mind about which answer is best, but eitherway think of the site as a wiki, there can be more than 1 good answer

    – Tom J Nowell
    Apr 10 at 17:21











  • One reason why I don't want to change answer is that I have conretely tested and applied the answer I selected as solution. Your answer brought more details and things I had thought in a wrong way somehow, but I haven't litteraly tested and checked it all. I also think that on most StackExchange sites, first good answers get selected, next one get votes. And though this has me scratching my head a bit, I see no reason to remove the solution rewards from the person who solved it first.

    – TTT
    Apr 10 at 17:42







1




1





Thank you for detailed explanation. I've already marked an answer that came quicker as solution however.

– TTT
Apr 10 at 15:25





Thank you for detailed explanation. I've already marked an answer that came quicker as solution however.

– TTT
Apr 10 at 15:25













You can change your mind about which answer is best, but eitherway think of the site as a wiki, there can be more than 1 good answer

– Tom J Nowell
Apr 10 at 17:21





You can change your mind about which answer is best, but eitherway think of the site as a wiki, there can be more than 1 good answer

– Tom J Nowell
Apr 10 at 17:21













One reason why I don't want to change answer is that I have conretely tested and applied the answer I selected as solution. Your answer brought more details and things I had thought in a wrong way somehow, but I haven't litteraly tested and checked it all. I also think that on most StackExchange sites, first good answers get selected, next one get votes. And though this has me scratching my head a bit, I see no reason to remove the solution rewards from the person who solved it first.

– TTT
Apr 10 at 17:42





One reason why I don't want to change answer is that I have conretely tested and applied the answer I selected as solution. Your answer brought more details and things I had thought in a wrong way somehow, but I haven't litteraly tested and checked it all. I also think that on most StackExchange sites, first good answers get selected, next one get votes. And though this has me scratching my head a bit, I see no reason to remove the solution rewards from the person who solved it first.

– TTT
Apr 10 at 17:42










TTT is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















TTT is a new contributor. Be nice, and check out our Code of Conduct.












TTT is a new contributor. Be nice, and check out our Code of Conduct.











TTT is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to WordPress Development Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fwordpress.stackexchange.com%2fquestions%2f333999%2fwhy-is-my-custom-api-endpoint-not-working%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020