Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress JSON API returns normal site page in html. How do I get it to give me JSON like it's supposed to

Tags:

json

wordpress

For example, entering http://mywordpresswebsite.example.com/?json=1 into the browser loads the main site html, the same as omitting the json querystring variable: http://mywordpresswebsite.example.com/

The JSON API is activated. I have tried reactivating and deactivating, checking .htaccess file settings, and deactivating all other plugins. None of those have made much difference so far.

TIA

like image 650
n8bar Avatar asked Apr 21 '17 15:04

n8bar


2 Answers

I'm likely doing it wrong, but when I form my requests for a Wordpress installation at http://www.example.com/ like this:

http://www.example.com/index.php?rest_route=/my/rest/route/here

I end up getting proper responses back.

I had a heck of a time figuring this out and ended up grokking a URL formatted like that in the HTML returned to me. I was expecting to make requests as http://www.example.com/wp_json/wp/v2/my/rest/route/here , but I only got HTML responses.

(FWIW, I am reposting this on all similar questions on the StackExchange network. Admins/mods - if this is against the rules or seen as rep spamming, feel free to take it down. Was hoping to help anyone else hitting the same issue I am, and to also learn what it is I've done wrong and why.)

like image 145
Mattygabe Avatar answered Nov 15 '22 01:11

Mattygabe


I had the same problem with my localhost test page and was wondering, why my route worked last week and was not accessible this week.

Short explanation

After some tests and a lot of frustration, I was able to use the REST API Route again by following the wordpress documentation about routes-vs-endpoints with “Pretty Permalinks” and “Ugly” Permalinks

Longer explanation

I guess in my case it was based on the reinstall of my MySQL Database. By installing the new database, my previous setup has been reset to the wordpress standard installation with permalinks as "plain", which is an "ugly" permalink. That's the reason, why the answer of Mattygabe work for me after the reinstall of the database.

But with this solution, I had a problem with my filter value and therefore I found the solution with "pretty premalinks" and changed my permalinks to "Month and name", as shown in the picture. After this change, I could access my REST API via the desired route.

enter image description here

There could be also some difficulties with REST APIs related to the following examples:

  • using "wp" within the REST route
  • if you work on plugins, which should be shared, keep on mind that some plugins may restrict REST Access, e.g. iThemes Security
like image 30
Rene Avatar answered Nov 14 '22 23:11

Rene