[wp-hackers] Building a JSON API style plugin

Mike Schinkel mikeschinkel at newclarity.net
Wed Nov 2 16:46:15 UTC 2011

On Nov 2, 2011, at 11:51 AM, Tom Barrett wrote:
> I want to add some trivial JSON requests to a site. I'm wondering if there
> is a best practice for this. I have various thoughts on this, but nothing
> terribly concrete yet.
> 1. Is template_redirect the best hook point?
> 2. If I don't want to use the query string (e.g. /api/ticket/1234.json)
> will I get caught up in the rewrite system?
> My initial version is this:
> add_action( 'template_redirect', 'get_ticket' );
> function get_ticket(){
>  $ticket = get_ticket_details($_GET['ticket']);
>  header('Content-Type: application/json');
>  echo json_encode($ticket);
>  exit(0);
> }
> Any glaring WordPress issues there? I appreciate there is no sanity or
> taint checking, but it seems that WordPress has a lot of tricks under it's
> hood and I'm trying not to rewrite the wheel.

ASSUMING you need to explicitly implement HTTP GET requests instead of POST requests (you can do POST with an existing API in WordPress) and that you don't need security, i.e. that anyone can access the ticket that wants to, here is my take.  Note that this probably needs to be made more robust in a few places regarding encodings; maybe others can help with that?


Also note that I used an /api/ prefix on the URL and I'm using clean URLs instead of $_GET parameters so your URLs would look like this:


Hope this helps.


More information about the wp-hackers mailing list