Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
86 views

Documentation To Connect A Simple Web App To Wp-Rest Api

The document provides instructions for creating a simple web app connected to the WordPress REST API. It explains what a REST API is and the basics of making requests to an API, including endpoints, methods, headers, and JSON response format. It then gives steps for setting up a WordPress blog with REST API and JWT authentication plugins to allow retrieving blog posts and submitting new posts via API requests from an app. Sample code is provided to retrieve blog posts from the API and display them on an app frontend.

Uploaded by

Adegoke Bestman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Documentation To Connect A Simple Web App To Wp-Rest Api

The document provides instructions for creating a simple web app connected to the WordPress REST API. It explains what a REST API is and the basics of making requests to an API, including endpoints, methods, headers, and JSON response format. It then gives steps for setting up a WordPress blog with REST API and JWT authentication plugins to allow retrieving blog posts and submitting new posts via API requests from an app. Sample code is provided to retrieve blog posts from the API and display them on an app frontend.

Uploaded by

Adegoke Bestman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

01/29/2020

DOCUMENTATION FOR CREATING A SIMPLE WEB APP CONNECTED


TO THE WORDPRES REST API
-OKOYE ONYEKACHI
What does REST API mean?
An API is an application programming interface. It is a set of rules that allow programs to
talk to each other. The developer creates the API on the server and allows the client to
talk to it.
REST determines how the API looks like. It stands for “Representational State Transfer”.
It is a set of rules that developers follow when they create their API. One of these rules
states that you should be able to get a piece of data (called a resource) when you link to
a specific URL.
Each URL is called a request while the data sent back to you is called a response.

The Anatomy Of A Request

It’s important to know that a request is made up of four things:

 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:

Let’s go through the rest of what makes up a request.


The Method
The method is the type of request you send to the server. You can choose from these five
types below:

 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.

The Data (Or “Body”)


The data (sometimes called “body” or “message”) contains information you want to be
sent to the server. This option is only used
with POST, PUT, PATCH or DELETE requests.

WordPress REST API

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

Signup, login and create a new website


Install WordPress
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 following

RewriteEngine on

RewriteCond %{HTTP:Authorization} ^(.*)

RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]


Scroll down to search for .htaccess, wp-config.php, wp-config.sample.php to make the
following edit

In the .htaccess file


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

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

For the wp-config.php and wp-config.sample.php

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.

Support and Requests please in Github: https://github.com/Tmeister/wp-api-jwt-auth

PHP HTTP AUTHORIZATION HEADER ENABLE

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} ^(.*)

RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

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

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

CONFIGURATION

CONFIGURATE THE SECRET KEY

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');

You can use a string from here https://api.wordpress.org/secret-key/1.1/salt/

CONFIGURATE CORS SUPPORT

The wp-api-jwt-auth plugin has the option to activate CORs support.

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

Mobile App setup

With the documentation from the apache cordova site, setup a new cordova project

Get Posts from Blog in the front-end


I have a simple template on how to display posts from the WordPress blog in the frontend
of our application.
Index.html

<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

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

 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

You might also like