Accessing the WordPress REST API - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Tuesday, December 15, 2020

Accessing the WordPress REST API

 For accessing WP-REST API, via the command line, use WP-CLI. which enables user to access the features without via your admin screens or by directly accessing the code on your site. Let’s take a look at how you get started.

Accessing WP-REST via WP-CLI

WP-CLI is the WordPress Command Line Interface. It lets you access and work with WordPress via the Command Line Interface (CLI) on your computer. To access the CLI, open Terminal on a Mac or in Linux, or Command Prompt in Windows.



To access a remote site, you need to SSH to your server to access it via WP-CLI 

To access a local site, you simply need to use the correct directory structure from the command line. It’s a good idea to experiment with the REST API on a local test site before trying it on a live site.You’ll need to specifically access the REST API for your site, like this: 

http://yoursite.com/wp-json/wp/v2

You can then add elements after this to access certain types of data, which we’ll look at in more detail shortly. These elements are called endpoints.

Authentication

Once you’ve accessed your site, you may need to go through authentication. Some endpoints are public and don’t require authentication, while others do. You’re not logging into your site admin here: the REST API does things a bit differently. To be able to authenticate your site via WP-CLI, you’ll need to install an authentication plugin. For development installations, the Basic Auth plugin does the job and is straightforward to work with. However, for live sites, you should use a more robust form of authentication such as the JWT Authentication plugin, which uses JSON Web Token and is more secure. You can then use the command line to access data and include authentication. The example below uses curl to test the connection to WordPress. It will output a list of draft posts.

curl -X GET --user username:password -i http://yoursite.com/wp-json/wp/v2/posts?status=draft

Draft posts aren’t public information, so you need authentication to access them. But if you’re looking for data that is public, you don’t need authentication. So to retrieve a list of posts which have been published, you could use:

curl -X GET http://yoursite.com/wp-json/wp/v2/posts

This would fetch all published posts because those are public.

No comments:

Post a Comment

Post Top Ad