Documentation To Connect A Simple Web App To Wp-Rest Api
Documentation To Connect A Simple Web App To Wp-Rest Api
The endpoint
The method
The headers
The data (or body)
The endpoint (or route) is the url you request for. It follows this structure:
The root-endpoint is the starting point of the API you’re requesting from. The root-
endpoint of Github’s API is https://api.github.com while the root-endpoint Twitter’s
API is https://api.twitter.com.
The path determines the resource you’re requesting for. Think of it like an automatic
answering machine that asks you to press 1 for a service, press 2 for another service, 3
for yet another service and so on.
You can access paths just like you can link to parts of a website. For example, to get a
list of all posts tagged under “JavaScript” on Smashing Magazine, you navigate
to https://www.smashingmagazine.com/tag/javascript/. https://www.smashingmagazine.
com/ is the root-endpoint and /tag/javascript is the path.
JSON
JSON (JavaScript Object Notation) a common format for sending and requesting data
through a REST API. The response that Github sends back to you is also formatted as
JSON.
A JSON object looks like a JavaScript Object. In JSON, each property and value must be
wrapped with double quotation marks, like this:
GET
POST
PUT
PATCH
DELETE
These methods provide meaning for the request you’re making. They are used to perform
four possible actions: Create, Read, Update and Delete (CRUD).
The Headers
Headers are used to provide information to both the client and server. It can be used for
many purposes, such as authentication and providing information about the body content.
You can find a list of valid headers on MDN’s HTTP Headers Reference.
HTTP Headers are property-value pairs that are separated by a colon. The example
below shows a header that tells the server to expect JSON content.
REQUIREMENTS
A web hosting service (e.g. 000webhost)
WordPress blog
REST API v2 plugin
JSON Web Token (JWT) Authentication plugin
Postman
HIGHLIGHTS
1. Create an account on 000webhost and host a WordPress blog.
2. Customize the WordPress blog(optional)
3. Install and configure the necessary plugins.
4. Get the jwt token using postman
5. Sending posts as JSON the WordPress blog
6. Get Posts from the blog.
Creating an account on 000webhost
To enable this option you’ll need to edit your .htaccess file adding the following
RewriteEngine on
To enable this option you’ll need to edit your .htaccess file adding the follow
See https://github.com/Tmeister/wp-api-jwt-auth/issues/1
Description
Extends the WP REST API using JSON Web Tokens Authentication as an authentication
method.
JSON Web Tokens are an open, industry standard RFC 7519 method for representing
claims securely between two parties.
Most of the shared hosting has disabled the HTTP Authorization Header by default.
To enable this option you’ll need to edit your .htaccess file adding the follow
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
WPENGINE
To enable this option you’ll need to edit your .htaccess file adding the follow
See https://github.com/Tmeister/wp-api-jwt-auth/issues/1
CONFIGURATION
The JWT needs a secret key to sign the token this secret key must be unique and never
revealed.
To add the secret key edit your wp-config.php file and add a new constant
called JWT_AUTH_SECRET_KEY
define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
To enable the CORs Support edit your wp-config.php file and add a new constant
called JWT_AUTH_CORS_ENABLE
define('JWT_AUTH_CORS_ENABLE', true);
After this go back to your WordPress dashboard and download JWT authentication for
WP REST API plugin
After installing activate the plugin
With the documentation from the apache cordova site, setup a new cordova project
<div class="app-content">
<div class="d-flex justify-content-center pt-2" id="spinner">
<div class="spinner-border text-primary"></div>
</div>
<div class="container pt-2" id="mainDiv">
</div>
<div class="container">
<h2>Submit a post</h2>
<form class="was-validated">
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-
control" id="title" placeholder="title of post" name="title"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-
feedback">Please fill out this field.</div>
</div>
<div class="form-group">
<label for="content">Content:</label>
<textarea name="content" id="content" cols="30" rows="3"
class="form-control"
required></textarea>
<div class="valid-feedback">Valid.</div>
<div class="invalid-
feedback">Please fill out this field.</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</div>
Index.js
$(document).ready(function () {
var rootUrl = 'https://wordpress-restapi-demo.000webhostapp.com/';
/**
* wordpress url to retrieve all posts from our blog
*/
const url = `${rootUrl}/wp-json/wp/v2/posts`;
/**
* wordpress url used to retrieve a token for authentication
*/
var tokenUrl = `${rootUrl}/wp-json/jwt-auth/v1/token`;
/**
* in this custom scenario, we will be creating posts via admin
* access however in complex cases you should be able to register
* new users, the admin username and password is needed to retrieve
* a token which will be attached
* as headers to subsequent requests for authentication
*/
var adminDet = {
username: YOUR-BLOG-ADMIN-USERNAME,
password: YOUR-PASSWORD
};
/**
* variable to store token retrived from the api
*/
var token;
loadData();
/**
* ajax post request to retrieve the token once the app loads
*/
$.post(tokenUrl, adminDet,
function (data, status) {
console.log("token: " + data.token);
token = data.token;
});
/**
* loadData() function makes a get request to retrieve
* all posts from the wordpress blog
*/
function loadData() {
$.getJSON(url, function (data) {
console.log(data);
/**
* removes the spinner once a response is gotten from the api
*/
$("#spinner").remove();
/**
* ensures that the div tag with id= mainDiv
* is empty before appending innerHtml to it
*/
$("#mainDiv").empty();
/**reiterates through each list in the json oblect
* while appending it to the div tag with id= mainDiv
*/
for (var i = 0; i < data.length; i++) {
var div = document.createElement('div');
div.innerHTML = `
<div class="card pt-1">
<div class="card-body">
<h4 class="card-title">${data[i].title.rendered}</h4>
<p class="card-text text-
wrap">${data[i].content.rendered}</p>
</div>
</div>
`;
$("#mainDiv").append(div);
};
});
}
/**
* on form submission
* submits the required parameters to create a new post in the
* wordpress blog
*/
$('form').submit(function (event) {
// stop the form from submitting the normal way and refreshing the pa
ge
event.preventDefault();
// get the form data
// there are many ways to get this data using jQuery (you can use the
class or id also)
var formData = {
title: $('input[name=title]').val(),
content: $('textarea[name=content]').val(),
status: 'publish'
};
console.log(formData);
$.ajax({
url: url,
method: 'POST',
data: JSON.stringify(formData),
crossDomain: true,
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + token
},
success: function (data) {
console.log(data);
/**
* refreshes app-content to display latest posts
*/
loadData();
},
error: function (error) {
console.log(error);
}
});
});
});
In order to test the app on your browser, you’ll have to disable web security,
Procedure to disable web security on chrome
On your desktop
Right click on the chrome icon
Select open file location
Open your cmd from that location then type
press enter
the new window which pops up has web security disabled and can be used for testing
purposes without running to issues related to cors.
Demo