Coder Social home page Coder Social logo

wp-api / wp-api Goto Github PK

View Code? Open in Web Editor NEW
4.0K 4.0K 657.0 7.86 MB

The WP REST API has been merged into WordPress core. Please do not create issues or send pull requests. Submit support requests to the forums or patches to Trac (see README below for links).

Home Page: https://developer.wordpress.org/rest-api/

License: GNU General Public License v2.0

Shell 0.70% PHP 93.60% JavaScript 5.70%

wp-api's Introduction

WP REST API v2.0 (formerly known as WP-API)

Access your WordPress site's data through an easy-to-use HTTP REST API.

Development is no longer taking place in this repository.

  • For support requests, use the WordPress forums.
  • For bugs and patches, use WordPress core Trac. Be sure to include full details and reproduction steps about the issue you are experiencing, and ideally a patch with unit tests.

The "develop" branch is version 2 which represents the last "beta" versions of the plugin. Read the documentation to introduce yourself to endpoints, internal patterns, and implementation details.

The "master" branch represents the legacy version of the REST API.

About

WordPress is moving towards becoming a fully-fledged application framework, and we need new APIs. This project was born to create an easy-to-use, easy-to-understand and well-tested framework for creating these APIs, plus creating APIs for core.

This plugin provides an easy to use REST API, available via HTTP. Grab your site's data in simple JSON format, including users, posts, taxonomies and more. Retrieving or updating data is as simple as sending a HTTP request.

Want to get your site's posts? Simply send a GET request to /wp-json/wp/v2/posts. Update user with ID 4? Send a PUT request to /wp-json/wp/v2/users/4. Get the page with slug "about-me"? GET /wp-json/wp/v2/pages?slug=about-me. Get all posts with the search term "awesome"? GET /wp-json/wp/v2/posts?search=awesome. It's that easy.

The WordPress REST API exposes a simple yet easy interface to WP Query, the posts API, post meta API, users API, revisions API and many more. Chances are, if you can do it with WordPress, the API will let you do it.

The REST API also includes an easy-to-use JavaScript API based on Backbone models, allowing plugin and theme developers to get up and running without needing to know anything about the details of getting connected.

Check out our documentation for information on what's available in the API and how to use it. We've also got documentation on extending the API with extra data for plugin and theme developers!

The API code in this plugin is currently integrated into core WordPress starting in 4.7.

Development is no longer taking place in this repository.

  • For support requests, use the WordPress forums.
  • For bugs and patches, use WordPress core Trac. Be sure to include full details and reproduction steps about the issue you are experiencing, and ideally a patch with unit tests.

Quick Setup

Want to test out the WP REST API? The easiest way is just to install a recent version of WordPress (4.7 or later).

Testing

You can also set up a development environment to work on the API code.

See the instructions for running the WordPress PHPUnit test suite to get started.

Issue Tracking

All tickets for the project are being tracked on WordPress core Trac.

Some previous issues can be found on the issue tracker for this repository; however, now that development of the API has moved to core Trac, new issues should not be filed here.

Contributing

Want to get involved? Check out Contributing.md for details on submitting fixes and new features.

Security

We take the security of the API extremely seriously. If you think you've found a security issue with the API (whether information disclosure, privilege escalation, or another issue), we'd appreciate responsible disclosure as soon as possible.

To report a security issue, you can either email security[at]wordpress.org, or file an issue on HackerOne. We will attempt to give an initial response to security issues within 48 hours at most, however keep in mind that the team is distributed across various timezones, and delays may occur as we discuss internally.

(Please note: For testing, you should install a copy of the project and WordPress on your own server. Do not test on servers you do not own.)

License

GPLv2+

wp-api's People

Contributors

afurculita avatar be-webdesign avatar danielbachhuber avatar danielpunkass avatar edhurtig avatar joehoyle avatar kadamwhite avatar kjbenk avatar mayukojpn avatar nikv avatar ntwb avatar nullvariable avatar nylen avatar osiux avatar patrickgalbraith avatar pento avatar pollyplummer avatar rachelbaker avatar rmccue avatar schlessera avatar shelob9 avatar soean avatar staylor avatar tharsheblows avatar thiago-negri avatar tierra avatar tlovett1 avatar tobych avatar websupporter avatar westonruter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wp-api's Issues

Number of posts per page

It could be nice if API users could set the number of desired posts returned per page (with a "/count" argument for example).
(Correct me if this functionality already exist, I didn't found anything like this).

Accept header mod_rewrites

This is more of a question than an issue. Are there any problems with doing this with the plugin implementation? I'm trying it out and seems fine so far.

.htaccess

# BEGIN wp-json
RewriteEngine On
RewriteCond %{HTTP:Accept} application/json
RewriteCond %{REQUEST_URI} !index\.php$
RewriteRule .* index.php?json_route=%{REQUEST_URI} [L,QSA]
# END wp-json

PHP Notice thrown if no created / published posts and requesting Custom Post Type

In this scenario, php returns a notice in which the $post object in wp-includes/post-template.php is null.

Notice:  Trying to get property of non-object in wp-includes/post-template.php on line 209

Again, the notice throws only when no posts are created / published and you are attempting to request a custom post type (ie wp-json.php/posts?type=custom_post_type)

Tested with:
WP 3.8.1
WP-API 0.8

Create Posts - Returns Missing Callback Error

Every time I try to create a posts with the api I get this as a response:

[1]
0:  {
code: "json_missing_callback_param"
message: "Missing parameter data"
}

I have tried both methods outlined here:
https://github.com/WP-API/WP-API/blob/5dfce405e8c84adf6e9491775eff22fe53725e21/docs/routes/posts.md#create-a-post

Any idea what I'm missing?

$.ajax({
            type:'POST',
            url:'/wp-json.php/posts',
            data:{
                'title': 'Test Title'
            },
            contentType: 'application/json',
            success: function(data, textStatus, jqXHR){
                console.log('post creation success! ' + textStatus);
            },
            error: function(jqXHR, textStatus, errorThrown){
                console.log('error creating post, ' + textStatus + ', ' + errorThrown);
            }
        });

Access Menu information via the API

I'm curious to know if there's any plan to support accessing WP's Menu structures via this API. I have a site where I'm interested in using a WP install to content-manage the menus, but won't be using WordPress's templating to render them—being able to get menu info via this API would be pretty cool.

If there's technical reasons not to do this, or if there's an existing path to get this information, I'd love to learn more.

Test CPT endpoints

See #99. We should extend this for CPTs, including ensuring that internal parts are overridden correctly.

Switch from /wp-json.php to a different location

For maximum server compatibility, we need to switch from using /wp-json.php, as some server setups cannot handle this correctly.

One of my nginx setups parses /wp-json.php/posts and tries to load wp-json.php directly without falling back to index.php afterwards. This could be an error on my end, but I'd bet it's fairly common.

The original point of this was to ensure that the API endpoint was always at the same place, even once merged (and assuming that wp-json.php gets dropped into the WP root directory). However, with support for RSD (#40), this isn't an issue. I'd rather we change it now in that case.

I think /wp-json/ should be a fairly non-conflicting endpoint (with /wp-api/ to be used eventually per #34).

How can i query for all posts with a `post_parent` id?

Apologies if this is the wrong place to ask. I am trying to retrieve all posts with a post_parent id of a certain kind. What I am trying to get is all the media attachments of a post, specifically all thumbnails. I looked into the source and enabled for testing purposes the private query parameters here: https://github.com/WP-API/WP-API/blob/master/lib/class-wp-json-posts.php#L98

curl -ig "http://example.com/wp-json.php/media?filter[post_parent]=4918" returns all attachments and curl -ig "http://example.com/wp-json.php/posts?filter[post_parent]=4918" an empty array.

Expose $post_id inside 'json_prepare_meta' filter in WP_JSON_Posts

I need to alter the output of some custom fields in the json object.
This is easy with 'json_prepare_meta' filter:
https://github.com/WP-API/WP-API/blob/master/lib/class-wp-json-posts.php#L629

The problem that in order to do so I figured out I really need to know $post_id
Inside that filter I only have access to $custom_fields, which holds the result of get_post_meta() and that's it.

It would be nice if besides $custom_fields one could access also to $post_id while filtering the post meta, just like one can while filtering prepare_post function.

Possible bug in how trailing slash is handled

wp-json.php/posts gives a list of posts, while wp-json.php/posts/ gives a list containing only the first post. Making it similar to wp-json.php/posts/1. This could be by design but I feel it's a bit counter intuitive. A more thorough discussion can be read at Stack Exchange - trailing-slash-in-restful-api.

UPDATE - forgot to bring my opinion to the table. IMHO wp-json.php/posts/ should be the URI to list the resources available (posts). Just like wp-json.php/posts

I'm a just beginning to use WP-API (or JSON-REST-API) and am just creating issues as I find them. Let me know if this is unappreciated (I realize that you are only in 0.8).

Raw data goes unused when sent to an endpoint.

In class-wp-json-server.php, when dispatching callbacks if an endpoint expects raw data that data will end up going unused breaking the endpoint:

elseif ( $supported & self::ACCEPT_RAW ) {
    $data = $this->get_raw_data();
}

Create unit tests

We should start working on unit tests for the API. I'd like to aim for >90% code coverage, ideally 100% if possible. As such, setting the milestone for 3 weeks from now so that we can get this done thoroughly.

Test response class

We should test the internal WP_JSON_Response class, and ensure that the default implementation behaves as expected.

Usage/Authentication: Edit/Delete/Post New

Hi there,
I am totally stuck at the following:

curl --data '{"title": "Hello Updated World!"}' \
    -H "Content-Type: application/javascript" \
    --user username:password \
    http://apitest.landwire.net/wordpress/wp-json.php/posts/1

Returns:

{"code":"json_cannot_edit","message":"Sorry, you are not allowed to edit this post."}
curl -X DELETE --user admin:password http://apitest.landwire.net/wordpress/wp-json.php/posts/1

Returns:

[{"code":"json_user_cannot_delete_post","message":"Sorry, you are not allowed to delete this post."}]

The password, user role (admin) and the username are correct.

I also tried this in case it was an authentication issue:

curl --data '{"title": "Hello Updated World!"}'  http://apitest.landwire.net/wordpress/wp-json.php/posts

As far as I could gather this should create a new post. Correct? I just get an Unknown Error back from the API. No idea where it fails, I looked into the code, but could not see a reason. Could it be a server issue?

I also tried various variations of the following in script form, always getting a "Bad Request" 400 Error:

function editPost(id) {

if(id) {    
   var the_url = 'http://apitest.landwire.net/wordpress/wp-json.php/posts/'+ id;
}
else {
   return;
}
    jQuery.ajax({
      url: the_url,
     //  headers: {
      //    'Authorization': "Basic " + btoa("username" + ":" + "password"),
      //    'Content-Type': 'application/javascript'
  //   },
headers: {
       "Authorization": "Basic " + btoa("username:password")
    },
//beforeSend: function (req) {
       // req.setRequestHeader('Authorization', //"username:password");
  //  },
    //  username: 'username',
   //  password: 'password',
      data: {
          'title': 'Hello Updated World!',
          'modified': '2013-04-01T14:00:00+10:00'
       },
      dataType: 'json',
      type: 'PUT',
      success: function(data) {
        var json_response = data;
        console.log('Updated Post ID ' + id + ': ', data);
       }
    });
}

Obviously the API must work for you guys, so any ideas what I am doing wrong?
Thanks,
Sascha

Possibility to filter Content-Type (and other headers)

We're using jQuery File Upload with iframe-transport to upload files to a custom API endpoint.

Due to IE:s lack of support for application/json responses to an <iframe>, we need this endpoint to return Content-Type: text/plain whenever application/json isn't accepted.

Would it be possible to add a filter to WP_JSON_Server::serve_request() (or wherever you se fit) so plugins can modify the response headers?

As a workaround, we've added this code at the top of serve_request():

header( 'Vary: Accept' );
if ( isset( $_SERVER['HTTP_ACCEPT'] ) && ( strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false ) ) {
    $this->header( 'Content-Type', 'application/json; charset=' . get_option( 'blog_charset' ), true );
} else {
    $this->header( 'Content-Type', 'text/plain; charset=' . get_option( 'blog_charset' ), true );
}

Fatal Error with JSON Response Interface preventing activation

Getting this error on wordpress 3.8.1

Fatal error: Can't inherit abstract function JsonSerializable::jsonSerialize() 
(previously declared abstract in WP_JSON_ResponseInterface) in 
../../wp-content/plugins/WP-API/lib/class-wp-json-responseinterface.php on line 3

Test taxonomy endpoints

We should ensure that taxonomy endpoints are tested, including custom taxonomies and built-in ones.

insert_post() method looks for post_type using key "type"

Post type is searched for in key named "type". This is inconsistent with WP core (https://codex.wordpress.org/Function_Reference/wp_insert_post) and undocumented within this plugin.

if ( ! empty( $data['type'] ) ) {
   // Changing post type
   $post_type = get_post_type_object( $data['type'] );
   if ( ! $post_type )
      return new WP_Error( 'json_invalid_post_type', __( 'Invalid post type' ), array( 'status' => 400 ) );

   $post['post_type'] = $data['type'];
}

Usage of `/pages` in the `WP_JSON_Pages` class

In line with the excellent advice from the doc on Extending the API:

You should also consider how other plugins might extend your data, and design for this.

I think it would be a good move to replace hardcoded references to the /pages base route in WP_JSON_Pages with $this->base.

Doing so would allow plugins to extend the WP_JSON_Pages class for custom post types that are very similar to the page post type and would benefit from methods like getPostByPath() etc. methods.

Rename all methods to fit coding standards

As per core coding standards, all methods should be renamed from semiCamelCase to underscore_case.

This is a backwards compatibility break, so for 0.8-1.0, let's ensure the sCC version is called if it exists (with _deprecated_function calls), but for 1.0, we should remove the BC shim.

DateTime::createFromFormat() bug when editing posts

Sorry been a while since I've had motivation to come back to working on my project, and help expand anywhere I can with this awesome plugin.

I recently did a full update of my code including merging all new aspects of your plugin with my outdated one. However I'm noticing a new error come up. Even though I pull from /posts and then edit using the same pulled object (editing title or content only) I am getting these errors on return:

Warning:
DateTime::createFromFormat() expects parameter 3 to be DateTimeZone, integer given in .. / lib / class - wp - json - datetime.php on line 16

Error:
Call to a member function setTimezone() on a non-object in .. / lib / class - wp - json - server.php on line 718

any ideas?

Add OAuth authentication

As discussed, we're moving ahead with OAuth authentication rather than Basic for future development. This ticket is to track that effort.

To start with, this will just be a custom authentication module on top of the existing Basic auth, but we'll rip Basic out at some point.

Remove references to IXR

We're no longer interfacing with legacy XML-RPC parts, so there's no need to reference anything relating to IXR, or load IXR at all.

Add endpoints to create, update and delete comments

This is a bit specific to my case, but figured it would be worth sharing how I added in new comments into the API.

public function newComment( $id, $data ) {
        $time = current_time('mysql');
        $data = array(
            'comment_post_ID' => $data['id'],
            'comment_author' => $data['author'],
            'comment_author_email' => $data['comment_author_email'],
            'comment_content' => $data['content'],
            'comment_date' => $time,
            'comment_approved' => 1
        );
        $newComment = wp_insert_comment($data);
        return $newComment;
}

I pass the ID into $data, but can easily just be grabbed from $id.

I will eventually be adding in logged in vs. not logged in, but I think that will primarily just be front end to retain as much of this API function as possible for either use case.

Unprefix everything

When we merge in to core, we need to unprefix everything. In case you were wondering why everything was prefixed with json_/WP_JSON_, this is why.

In reality, we're not so much unprefixing as we are switching prefixes. I'd like to use api_/WP_API_ for the prefix, since the API is more generic than just JSON, but this depends on what the core team thinks.

Remove Basic authentication

This relies on #32 getting merged, after which Basic authentication can be removed and/or moved to a separate plugin to help development.

Pass post_ID to json_insert_post

The post ID should be passed when invoking "json_insert_post" (class-wp-json-posts.php:864)

When updating a post, the $data array contains the Post ID.
That's not true for new posts, however.

so what about

do_action( 'json_insert_post', $post, $post_ID, $data, $update );

instead of

do_action( 'json_insert_post', $post, $data, $update );

??

Thank you.

json_prepare_attachment in WP_JSON_Media filter does not pass attachment data

Hi,

I am trying to augment attachment data and was trying to use the

json_prepare_attachment filter provided on line 127 of WP_JSON_Media

but parameters $data and $post

seem to be holding attachment parent data

calling

mydomain.dev/wp-json.php/media/285

with an action added to the hook like so

function my_prepare_attachment($data, $post, $context) {

  echo $data['ID']);
  exit;

}
add_action( 'json_prepare_attachment', 'my_prepare_attachment', 10, 3 );

echoes the attachment parent ID

which keeps me from being able to add anything to the attachment data

this seems to be caused by this block in WP_JSON_Post starting line 558

if ( 'view' === $context && 0 !== $post['post_parent'] ) {
            // Avoid nesting too deeply
            // This gives post + post-extended + meta for the main post,
            // post + meta for the parent and just meta for the grandparent
            $parent = get_post( $post['post_parent'], ARRAY_A );
            $post_fields['parent'] = $this->prepare_post( $parent, 'parent' );
        }

the recursive call at this point seems to mess things up - or I might be missing something

I can pass a different $context as a workaround for now but is it expected behavior?

thanks for any input on this

WP_JSON_Posts->prepare_author() needs check that $user exists

In the prepare_author method there is a conditional early return if the $author parameter wasn't passed, we should add an additional condition to verify the $user object was returned.

This is a minor bug in the logic, but it can happen if a user account was removed but the deleted user's posts weren't re-assigned.

Pull request with minor fix forthcoming.

404 when filtering by post type

Hi,

I have a strange problem when I try to make this plugin work on one site I recently got from a client.

When I try to access http://lpdf.dev/wp-json.php/posts, everything works smoothly, I can see my posts of different types.

But when I query http://lpdf.dev/wp-json.php/posts?type=faute (faute is a custom type) or even http://lpdf.dev/wp-json.php/posts?type=post I get a 404 status code AND some data in my JSON :-/

WordPress is v3.6.1. Any idea how to fix or at least debug this?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.