GithubHelp home page GithubHelp logo

wp-cli / restful Goto Github PK

View Code? Open in Web Editor NEW
146.0 21.0 14.0 191 KB

Unlocking the potential of the WP REST API at the command line

Home Page: https://wp-cli.org/restful/

License: MIT License

PHP 90.67% Shell 1.06% Gherkin 8.27%
wp-cli wp-cli-package rest-api wordpress rest api cli hacktoberfest

restful's Introduction

wp-cli/restful

Unlock the potential of the WP REST API at the command line.

Warning: This project is at a very early stage. Treat it as an experiment, and understand that breaking changes will be made without warning. The sky may also fall on your head. Using RESTful WP-CLI requires the latest nightly build of WP-CLI, which you can install with wp cli update --nightly.

Initial development was backed by a Kickstarter project. This project will evolve alongside the WP REST API's evolution in WordPress core.

Build Status

Quick links: Using | Installing | Contributing | Support

Using

RESTful WP-CLI makes WP REST API endpoints available as WP-CLI commands.

As WordPress becomes more of an application framework embedded into the web, RESTful WP-CLI enables WP-CLI users to interact with a given WordPress install through the higher-level, self-expressed abstraction of how WordPress understands itself. For instance, on an eCommerce website, instead of having to know data is stored as wp post list --post_type=edd_product, RESTful WP-CLI exposes the properly-modeled data at wp rest product list.

Here's an overview of how RESTful WP-CLI works, in two parts.

1. Auto-discovers WP REST API endpoints from any WordPress site running WordPress 4.7 or higher

Target a specific WordPress install with --path=<path>, --ssh=<host>, or --http=<domain>:

# The `--path=<path>` global parameter tells WP-CLI to interact with a WordPress install at a given path.
# Because this is a stock WordPress install, you see the posts, pages, and other resources you'd expect to see.
$ wp --path=/srv/www/wordpress-develop.dev/src rest
usage: wp rest attachment <command>
   or: wp rest category <command>
   or: wp rest comment <command>
   or: wp rest page <command>
   or: wp rest page-revision <command>
   or: wp rest post <command>
   or: wp rest post-revision <command>
   or: wp rest status <command>
   or: wp rest tag <command>
   or: wp rest taxonomy <command>
   or: wp rest type <command>
   or: wp rest user <command>

# The `--http=<domain>` global parameter tells WP-CLI to auto-discover endpoints over HTTP.
# Because Wired has some custom post types, they're automatically registered as WP-CLI commands.
$ wp --http=www.wired.com rest
usage: wp rest attachment <command>
   or: wp rest category <command>
   or: wp rest comment <command>
   or: wp rest liveblog <command>
   or: wp rest liveblog-revision <command>
   or: wp rest page <command>
   or: wp rest page-revision <command>
   or: wp rest podcast <command>
   or: wp rest post <command>
   or: wp rest post-revision <command>
   or: wp rest series <command>
   or: wp rest slack-channel <command>
   or: wp rest status <command>
   or: wp rest tag <command>
   or: wp rest taxonomy <command>
   or: wp rest type <command>
   or: wp rest user <command>
   or: wp rest video <command>

# The `--ssh=<host>` global parameter proxies command execution to a remote WordPress install.
# Because runcommand has a completely custom data model, you can only interact with commands, excerpts, and sparks.
$ wp --ssh=runcommand.io rest
usage: wp rest command <command>
   or: wp rest excerpt <command>
   or: wp rest spark <command>

2. Registers WP-CLI commands for the resource endpoints it understands, in the wp rest namespace.

In addition to the standard list, get, create, update and delete commands, RESTful WP-CLI also registers commands for higher-level operations like edit, generate and diff.

# In this example, `@wpdev` is a WP-CLI alias to `--path=/srv/www/wordpress-develop.dev/src`.
$ wp @wpdev rest user
usage: wp rest user create --username=<username> [--name=<name>] [--first_name=<first_name>] [--last_name=<last_name>] --email=<email> [--url=<url>] [--description=<description>] [--nickname=<nickname>] [--slug=<slug>] [--roles=<roles>] --password=<password> [--capabilities=<capabilities>] [--porcelain]
   or: wp rest user delete <id> [--force=<force>] [--reassign=<reassign>] [--porcelain]
   or: wp rest user diff <alias> [<resource>] [--fields=<fields>]
   or: wp rest user edit <id>
   or: wp rest user generate [--count=<count>] [--format=<format>] --username=<username> [--name=<name>] [--first_name=<first_name>] [--last_name=<last_name>] --email=<email> [--url=<url>] [--description=<description>] [--nickname=<nickname>] [--slug=<slug>] [--roles=<roles>] --password=<password> [--capabilities=<capabilities>] [--porcelain]
   or: wp rest user get <id> [--context=<context>] [--fields=<fields>] [--field=<field>] [--format=<format>]
   or: wp rest user list [--context=<context>] [--page=<page>] [--per_page=<per_page>] [--search=<search>] [--exclude=<exclude>] [--include=<include>] [--offset=<offset>] [--order=<order>] [--orderby=<orderby>] [--slug=<slug>] [--roles=<roles>] [--fields=<fields>] [--field=<field>] [--format=<format>]
   or: wp rest user update <id> [--username=<username>] [--name=<name>] [--first_name=<first_name>] [--last_name=<last_name>] [--email=<email>] [--url=<url>] [--description=<description>] [--nickname=<nickname>] [--slug=<slug>] [--roles=<roles>] [--password=<password>] [--capabilities=<capabilities>] [--porcelain]

# Use `wp rest * edit` to open an existing item in the editor.
$ wp rest category edit 1 --user=daniel
---
description:
name: Uncategorized
slug: uncategorized
parent: 0

# Use `wp rest * generate` to generate dummy content.
$ wp @wpdev rest post generate --count=50 --title="Test Post" --user=daniel
Generating items  100% [==============================================] 0:01 / 0:02

# Use `wp rest * diff` to diff a resource or collection of resources between environments.
$ wp @dev-rest rest command diff @prod-rest find-unused-themes --fields=title
(-) http://runcommand.dev/api/ (+) https://runcommand.io/api/
  command:
  + title: find-unused-themes

If WP-CLI is operating directly against a WordPress install, you can use the --debug flag to track the number of queries and total execution time. This can be useful for measuring and profiling API requests.

$ wp rest category list --debug
Debug (rest): REST command executed 3 queries in 0.000311 seconds. Use --debug=rest to see all queries. (1.118s)
+---------------+
| name          |
+---------------+
| Test Category |
| Uncategorized |
+---------------+

There are many things RESTful WP-CLI can't yet do. Please review the issue backlog, and open a new issue if you can't find an exising issue for your topic.

Installing

Installing this package requires WP-CLI 1.3.0-alpha or greater. Update to the latest nightly release with wp cli update --nightly.

Once you've done so, you can install this package with wp package install wp-cli/restful.

Contributing

We appreciate you taking the initiative to contribute to this project.

Contributing isn’t limited to just code. We encourage you to contribute in the way that best fits your abilities, by writing tutorials, giving a demo at your local meetup, helping other users with their support questions, or revising our documentation.

For a more thorough introduction, check out WP-CLI's guide to contributing. This package follows those policy and guidelines.

Reporting a bug

Think you’ve found a bug? We’d love for you to help us get it fixed.

Before you create a new issue, you should search existing issues to see if there’s an existing resolution to it, or if it’s already been fixed in a newer version.

Once you’ve done a bit of searching and discovered there isn’t an open or fixed issue for your bug, please create a new issue. Include as much detail as you can, and clear steps to reproduce if possible. For more guidance, review our bug report documentation.

Creating a pull request

Want to contribute a new feature? Please first open a new issue to discuss whether the feature is a good fit for the project.

Once you've decided to commit the time to seeing your pull request through, please follow our guidelines for creating a pull request to make sure it's a pleasant experience. See "Setting up" for details specific to working on this package locally.

Support

GitHub issues aren't for general support questions, but there are other venues you can try: https://wp-cli.org/#support

This README.md is generated dynamically from the project's codebase using wp scaffold package-readme (doc). To suggest changes, please submit a pull request against the corresponding part of the codebase.

restful's People

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

restful's Issues

Support oAuth 1.0a and Broker authentication

To make it easier to authenticate against remote sites, it would be helpful to support oAuth 1.0a and Broker authentication.

We may need to cache credentials somewhere on the filesystem, to prevent having to auth with every request.

Previously #11

Provide dummy data to generated resources

Because we have access to the JSON schema for each resource, we have some understanding of the expected data for each field. We should use this knowledge to provide dummy data to generated resources.

Previously #55

Include --sudo mode

In local environments, where we have direct access to the database, we could have a --sudo flag which would run as user 0 and grant all capabilities. This would mirror WP-CLI's current behavior for CRUD operations.

Make `--http=<domain>` a global argument

Currently, we have to register --http=<domain> as an assoc argument so WP-CLI's synopsis parser doesn't error on it:

$synopsis[] = array(
    'name'        => 'http',
    'type'        => 'assoc',
    'optional'    => true,
);

It would be better to be able to register --http=<domain> as a global argument, in such a way it doesn't get treated as a command argument (both with the synopsis parser, and passed through as $assoc_args)

From #8

Edit any resource in EDITOR

WP-CLI has wp post edit, which loads the post content in the editor. It would be cool if you could edit any REST resource in the editor.

More efficiently compare two resources

Currently, wp rest * diff fetches an entire collection in order to compare a given resource.

If a specific resource is to be compared, we should only fetch that data for comparison.

From #75, #56

Support --format=summary when diffing a collection

When diffing a large collection, the amount of output can be too much process.

With a --format=summary argument, we could present a summary of the difference to the end user, empowering them to better understand the differences.

From #75, #56

Cannot fetch a field property such as content.rendered

The following command returns the content of a post:

wp rest post get 1 --field=content

A problem that arises is that the content field is a JSON object containing properties such as rendered and private.

It's not possible to directly access these field properties in order to get their textual value. A utility such as jq has to be used on the CLI to drill down to a given property.

A syntax such as the following would be useful:

wp rest post get 1 --field=content.rendered

travis is failing in before_script stage

Travis is failing at beginning/core. I've made no changes. Therefore, its something wrong with travis or with the install procedures you configured. Or perhaps travis made changes and now your install procedures are outdated.

The error is:

install_db
+mysql -e 'CREATE DATABASE IF NOT EXISTS wp_cli_test;' -uroot
+mysql -e 'GRANT ALL PRIVILEGES ON wp_cli_test.* TO "wp_cli_test"@"localhost" IDENTIFIED BY "password1"' -uroot
0.19s$ ./vendor/bin/behat

[Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException]                             
  Circular reference detected for service "gherkin", path: "gherkin -> gherkin.loader.feature_suite -> gherkin".

Error: 'rest' is not a registered wp command. See 'wp help'.

Hi ther

After installing the package as stated in the readme-file I get the error (though I could not update the wp-cli --nightly as plain user, so I did that as root user...) :

Error: 'rest' is not a registered wp command. See 'wp help'.

when doing a 'wp' the rest comand is as suspected not in the list... is there a way to activate the package if this has not been done in the installation process ?

Cheers
Adam

Inject schema details into the YAML doc as comments

Editing a post looks like this:

image

YAML supports comments, so it would be cool if we injected comments from the schema about the resource into the document. For instance, any enum like status could indicate accepted values. And, of course, we can list the property description.

From #51

Non-static method called statically.

Hi there,

Let me start by saying my PHP skills are terrible, so if this isn't an issue I apologize for bringing it up.

After installing this package, I received some errors in the console related to this method being called statically (on line 86 of the same file) when it's not written as a static method.

Thanks for your work on this. Looks pretty awesome. 👍

Standalone PHP REST client

This only occurred to me today after taking a quick look at the codebase, but I realized there's two things being developed here:

  1. WP REST API client
  2. WP-CLI plugin

Since you're doing most of the hard work for 1., it would be great to have a separate standalone PHP library (and Composer package) that could be used on its own.

This package/plugin could then use the client as a dependency and it would be pretty minimal.

I'd say the main question is around distributing this package. Not sure how WP-CLI packages handle dependencies.

Paginate through an entire collection

When comparing collections of resources from two different WordPress environments, we currently only fetch one page of results.

To accurately diff a collection, we should paginate through all resources.

From #75, #56

--format parameter conflicts with core WP arguments

--format is not a safe parameter name to use for diff or for generate.
Why?
Because format is a common name for arguments in core WP REST. Easy example is for posts.
Posts have a non-required argument "format" for the POST method endpoint like this:

"format": {
  "required": false,
  "enum": ["standard",
    "aside",
    "image",
    "video",
    "quote",
    "link",
    "gallery",
    "audio"],
  "description": "The format for the object.",
  "type": "string"
}

I recommend to change everywhere this wp-cli --format parameter to something else.
I recommend "--outputformat" and it to be changed throughout the code, e.g. in generate, diff, get, list, ...

Extend documentation with more examples, http use

I was trying to install WP theme via http. Used this command:
wp theme install https://wordpress.org/themes/adaption/ --allow-root --http=http://video.xxxxxxxxxx.info/ --debug Debug (bootstrap): No readable global config found (0.006s) Debug (bootstrap): No project config found (0.006s) Debug (bootstrap): Loading packages from: /root/.wp-cli/packages/vendor/autoload.php (0.094s) Debug (rest): No schema title found for /, skipping REST command registration. (0.795s) Debug (rest): No schema title found for /oembed/1.0, skipping REST command registration. (0.796s) Debug (rest): No schema title found for /oembed/1.0/embed, skipping REST command registration. (0.796s) Debug (bootstrap): ABSPATH defined: / (0.797s) Error: This does not seem to be a WordPress install. Pass --path=path/to/wordpressor runwp core download.

The website of course is a WP install, so i am not sure what is the problem, but i think i may be missing something in the params.
I am pretty sure there also needs to be username and pw in the params for it to work, but i dont see that in global params.

How to load restful in windows

How to load restful API in windows as after running command
wp --http=http://127.0.0.1/mysite/
I get Error
Error: RESTful WP-CLI needs to be installed. Try 'wp package install wp-cli/restful'.
Upon installing successfully I get same Error every time
Here is the installation Log

Installing package wp-cli/restful (dev-master)
Updating C:\Users\Ashish/.wp-cli/packages/composer.json to require the package...
Using Composer to install the package...
---
Loading composer repositories with package information
Updating dependencies
Resolving dependencies through SAT
Dependency resolution completed in 0.169 seconds
Analyzed 4353 packages to resolve dependencies
Analyzed 168589 rules to resolve dependencies
Package operations: 1 install, 0 updates, 0 removals
Installs: wp-cli/restful:dev-master 4194f57
 - Installing wp-cli/restful (dev-master 4194f57)
Writing lock file
Generating autoload files
---
Success: Package installed.

Also tried to place the files in c:\wp-cli.wp-cli...
But that too doesn't help. Any solution for Windows Users?

Deregister default PTCU commands

When wp-rest-cli is enabled, we should deregister the default PTCU commands, as we're opinionated towards managing WordPress through the REST API.

Cache --http lookup requests

When the --http=<domain> parameter is provided, we make a HEAD request to get the index URL, and then a GET request to wp-json/?context=help to get the full index.

Ideally, the result of these requests should be cached, so we only need to make extra requests when we initially prime the cache, and occasionally refresh it.

Related #9
From #8

Don't require `class_exists( 'WP_CLI' )` conditionals to be used in wp-rest-cli.php

In a941ff0, I had to add a conditional around the loading of the command code because otherwise it causes a fatal when the tests are running.

The fatal happens when tests are running because our autoload->files declaration in composer.json loads wp-rest-cli.php when we're calling the behat binary.

The conditional sucks, though. We should figure out if we can get the autoload definition in there without actually autoloading in this context.

wrong schema loaded for commands causes fault

fail case:
wp-cli --http=myserver.com rest user list

result:
Error: Invalid field: password.

I believe this is due to the wrong schema being loaded. The schema for POST on the user route is used with a list command. It should use the GET schema since this is a list command. Specifically in this scenario, the core WP rest routes define the password field as required in the POST schema. Same time, the password field is absent from the GET schema. When the core WP REST api returns results for users, it does not send a password field. This causes a fault in the wpcli formatter because it tries to access a password field on the array.

Make `wp rest *` commands more accessible

Currently, all dynamically defined commands are in a wp rest * namespace to prevent collision with other commands. This means you have to type an extra 5, repeated characters (aka ' rest') every time you want to run a RESTful WP-CLI command.

It would be nice to make these commands more accessible in some way.

Related #1, #37

Call for feedback from theme and plugin authors

If you've written WP REST API endpoints for your theme or plugin, I'd love to hear your feedback on RESTful WP-CLI.

Feel free to drop a link to your repo if you want feedback on your WP REST API or WP-CLI implementation.

Generate new resources

WP-CLI has wp post generate, wp comment generate and others. We should introduce wp rest * generate, for generating arbitrary REST resources.

Add a basic clone operation

As a RESTful WP-CLI user, it would be useful if I could clone some amount of data from one environment to another.

Support authentication against remote sites

Many remote operations require authentication. We should have a way of authenticating against these sites (either providing access details at runtime, or storing them in some manner).

From #8

Strongly consider the implications of using HTTP status headers as return codes.

In #92, the return logic became:

if ( ( $status < 400 ) && ( isset( $body['previous']['id'] ) || isset( $body['id'] ) ) ) {
 +				// handles cases where user forget to put a value for --force=<value>
 +				WP_CLI::line( isset( $body['previous'] ) ? $body['previous']['id'] : $body['id'] );
 +			} else {
 +				WP_CLI::halt( $status );
 +			}

We should come to a final determination of whether this implementation makes sense.

cc @diablodale

Put together a README

For those wanting to learn more about the project, it would be good to have a README providing:

  • What the package does.
  • How to install / use it.
  • A high-level overview of how it works.
  • How to contribute.

Package install command fails for restful under certain reproducible circumstances

Hi there,

I've tried this command with several other wp-cli packages and it seems to only fail with this package.

this command works perfect:

wp package install wp-cli/restful --allow-root

this command does not:

wp package install wp-cli/restful --quiet --allow-root

any ideas? (note: the allow-root is used due to this being done in a docker container on build and I'm being too lazy to create a user and give permissions to that user for the composer directory)

--debug support for endpoint registry

Because we're particular about the endpoints we actually register as commands, let's scatter some WP_CLI::debug() throughout the registration process to give end users more visibility into which endpoints are registered, and which aren't.

missing license information

Standard licensing information is missing from this project.

  • I could find it in only one place -- within composer.json having Daniel's name and the license=MIT.
  • The LICENSE file is missing
  • licensing headers are missing in the two core files implementing restful: inc/RestCommand.php and inc/Runner.php.

Since the composer file in this repro names MIT and the wp-cli repro uses MIT, I suspect the intention is to make claim via the MIT license.

I can add the LICENSE file to have daniel's name as original author of the code and mine as additional author of all my commits; all using the same MIT license. I can also update composer's json to include my name as another author.

If, instead, the license is to be granted by contributors of restful (like done in wp-cli), then please clarify that and I'll use that nomenclature instead and adjust composer.json and a new LICENSE file both -- basically copying the approach of wp-cli.

Please note, attribution and reputation are both important in today's development industry. It is important to me that my code and anyone else's for restful have attribution directly or via a group of which these authors are a member.

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.