Licenta En 2019 [611674]

1
BABEȘ -BOLYAI UNIVERSITY
Faculty of Economics and Business Administration
Business Computer Science

BA Graduation Dissertation

Graduate,
Cosmin-Liviu MILCHIS

Supervisor,
Lecturer Alexandru STAN, PhD

2019

i
BABEȘ -BOLYAI UNIVERSITY
Faculty of Economics and Business Administration
Business Computer Science

BA Graduation Dissertation

Implementing a knowledge sharing web application
using WP Rest API and React.js

Graduate,
Cosmin-Liviu MILCHIS

Supervisor,
Lecturer Alexandru STAN, PhD

2019

ii

Abstract
This thesis deals with the creation of a web application using an instance of WordPress for
the back -end and an front -end built in React.js that is fed data from the WordPress installation
using the WP Rest API. In my opinion, this kind of web application will represent a big part in the future evolution of WordPress. I have identified a number of benefits from using
Wordpress as an Headless CMS, only for the back- end, but the main benefit is that web
developers are no longer rest ricted to using the classic PHP WordPress theming convention
for creating the front -end of the website. Instead, they can choose whatever technology they
are more familiar to build the fron t-end side of the website, while still maintaining the
Wordpress admin area, to which many final users are already accustomed. I also showed in
this thesis that using WordPress as a Headless CMS helps any developer build easier and
faster a Minimum Via ble Product ( MVP ) for a web application.

iii
Contents
List of tables and figures ……………………………………………………………………………………………………… iv
Introduction …………………………………………………………………………………………………………………………. 1
1. Business and competition analysis ……………………………………………………………………………………… 3
1.1 Why is Knowledge Sharing Important ……………………………………………………………………………… 4
1.2 Benefits of a Knowledge Sharing Application ………………………………………………………………….. 4
1.3 Difference between Data, Information & Knowledge ………………………………………………………… 5
2. Technologies used for this project ……………………………………………………………………………………… 7
2.1 WordPress ……………………………………………………………………………………………………………………. 7
2.2 WP Rest API ………………………………………………………………………………………………………………… 8
2.2.1 Why use the WordPress REST API ………………………………………………………………………….. 16
2.2.2 How does the WordPres s REST API work ………………………………………………………………… 16
2.3 React JS ……………………………………………………………………………………………………………………… 18
2.4 How Will It All Work Together …………………………………………………………………………………….. 20
3. Knowledge Sharing App – A WP Rest API & React.js Web Application …………………………… 22
3.1. About the application and it’s use cases ………………………………………………………………………… 22
3.1.1 Login pag e …………………………………………………………………………………………………………… 24
3.1.2 Dashboard/User Profile page …………………………………………………………………………………. 25
3.1.3 Available Articles page ………………………………………………………………………………………….. 25
3.1.4 Single Article page ………………………………………………………………………………………………… 25
3.1.5 Add New Article page ……………………………………………………………………………………………. 25
3.1.6 Review Article page ………………………………………………………………………………………………. 25
3.1.7 User Statistics page ……………………………………………………………………………………………….. 25
3.2. Designing the system ………………………………………………………………………………………………….. 26
3.3. Implementing the solution …………………………………………………………………………………………… 26
Phase One – Back -end ………………………………………………………………………………………………………. 26
Phase Two – Front -End …………………………………………………………………………………………………….. 29
3.4. Class D iagram ……………………………………………………………………………………………………………. 29
3.5. Activity Diagram ……………………………………………………………………………………………………….. 29
3.5.1 Manage Article Activity Diagram ……………………………………………………………………………. 30
3.5.2 Manage User Activity Diagram ………………………………………………………………………………. 31
3.6. Collaboration Diagram ………………………………………………………………………………………………… 33
3.7. Components Diagram …………………………………………………………………………………………………. 33
3.8. Exploa tation Diagram …………………………………………………………………………………………………. 34
3.9. Sequence Diagram ……………………………………………………………………………………………………… 35
3.10. Data Base View ………………………………………………………………………………………………………… 36
4. Tes ting the application ……………………………………………………………………………………………………. 38
4.1. What is web testing …………………………………………………………………………………………………….. 38
4.2. Tes ting WordPress and the custom plugin ……………………………………………………………………… 38
4.3. Testing the API endpoints with Postman ……………………………………………………………………….. 39
4.4. Manual functional & visual testing ……………………………………………………………………………….. 40
4.5. Automated re gression testing ……………………………………………………………………………………….. 40
Conclusions ………………………………………………………………………………………………………………………… 42
Remarks: ……………………………………………………………………………………………………………………………. 43
Annexes ……………………………………………………………………………………………………………………………… 44

iv
List of tables and figures
(blank line, 12pt, 1.5 spacing, no spaces before and after paragraph)
Tables:
1.Concise and relevant table title …………………………………………………. Error! Bookmark not defined.

Figures:
1. Concise and relevant figure title ………………………………………………. Error! Bookmark not defined.

Remarks:
Include only if your thesis contains a signi ficant number of tables/figures (at least 10). Formatting of
the listed table and figure titles : TNR, 11p, single spacing. Although an option, we do not recommend
differentiation between figures (schemes, diagrams, mechanisms, images) and graphs (dynamics of
certain quanti tative variables). Consequently, ”figure” covers graphs as well. Similarly, there is no
need for descriptions like ”Table no. 1: The banking system…” immediately under the headword
”Tables”; simple numbering (1, 2…) will suffice. We recommend generating the table and figure lists
automatically, using the Insert Table of Figures option, separately for tables and figures respectively,
after the tables/figures within the thesis have been previously numbered accordingly ( tables and
figures separately), using the Insert Caption option. To ensure that the formatting requirements for
tables/figures are met, use the Modify option available for Table of Figures . Remember to update the
lists (using the Update field option) to include the changes r esulted from your supervisor’s feedback.

1
Introduction
I have chosen this topic taking into consideration a need visible in multiple companies: the
need to share the knowledge. Every time a company brings in a new employee, they need to
bring him or her up to speed with the company’s procedures, tools, the ski lls needed,
basically any information the new employee needs to do his job more effectively. But a more
important need of the company is when an employee leaves. He/she usually takes the
knowledge he or she has accumulated over the years to the new employer, leaving the
company without something valuable. That information.
So, to come to the aid of the companies, I have decided to build a knowledge sharing web
application that will allow companies to share the knowledge to all it’s employees, but more
so, to keep the knowledge accumulated by the employees that are leaving. How? By having
those employees sharing their knowledge with the rest of the team during their tenure with
the company. Therefore, any company that intends to reduce the time and the costs with
workforce education needs access to such a platform for knowledge sharing.
In today’s digital world many websites or application like Khan Academy or Sparkyn enables
knowledge or talent sharing between individuals and/or within teams. The individuals can
easily reach to the people who want to learn, share their talent and get rewarded. So this web
application wi ll surely not be the best on the market, but instead wil l be more oriented on just
sharing the knowledge between teams. Of course, there will be articles that can be shared
with anyone that has an account, not just with your team.
For this project I have decided to use WordPress as a headless CMS , and the WordPress
REST API to feed data into a simple React .js web interface following the steps below :
• Creating custom post types and taxonomies in WordPress
• Mapping custom fields to JSON payload
• Consuming the J SON REST API with React
• Rendering the articles in our web interface, based on availabilit y.
Using this approach in building my Knowledge Sharing Web Application was an fairly easy
decision, mainly because of my experince in the last three to four years wit h using and
building WordPress based websites, but also because of all the benefits coming from using a
library like React JS for the front -end interface.
There are a number of benefits from using this approach when creating a web applica tion.
First of all, when you have to test your idea, to see if it’s fesable from a business stand point,
you should always take into consideration the Sunk Cost. By defintion, the sunk cost is a

2
cost that cannot be recovered. When creating a web applica tion, you need to keep the costs at
a minimum until you validate the idea. So you don’t invest so much in it from the beginning,
that at the point when you see that the idea is not fesable or profitable, you cannot let go
because of the important material and emotional i nvestment you have made into that product
or application. That’s why this approach is suitable for creating a Minimum Viable Product for a web application. You use open source platforms for creating the application and the cost
of the develo pment of the MV P is much lower than creating using other programming
languages/platforms.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
3
1. Business and competition analysis
At first look, you could say that there are a lot of knowledge sharing web applications on the
market today and you could be correct. But, when you take a more in- depth look at what the
big companies offer into the market, you see that there is a place for everybody under the sun.
Today, there are a big number of cloud- based apps targeted towards producti vity and
collaboration, like chat a pps, email apps, customer service and issues tra cking apps, etc. But
the big number of apps used by an organization brings a vast amount of data, both structured
and not structured, via documents, emails or chat messages, which makes it harder for the
end-user to search and find data across the organisation.

There are already well-established players in the knowledge sharing market, which is divided
by the type of the users. We have enterprise players like Microsoft, Coveo and Lexalytics ,
that lead the enterprise market, but they are geared for larger organisations and specifically
for search functionalities . Then we have te internal wikis and intranets like Atlassian’s
Confluence and Sharepoint, where teams update documents, but these spaces are very
difficult to maintain because the maintainance is done manually.
There are a number of startups emerging in the knowledge management space, but most of them concentrate on a united search space across all the business apps or a w rapper around all
the used desktop apps. That tells us that there is still space for a new app to enter the market,
as long as it brings a new and fresh solution on the knowledge management problem. It
would also help if the solution would be simple to use .

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
4
1.1 Why is Knowledge Sharing Important
When looking at the findings of the IDC analysis in the paper “ The Knowledge Quotient”
that „ 36% of a typical knowledge worker’s day is spent looking for and consolidating
information spread across a variety of systems” and that „these workers can find the
information required to do their jobs only 56% of the time” , it’s clear that any organisation’s
knowledge fragmentation leads to a massive decrease of productivity. More so, the same
analysis has found that „40% of employees are poor at tr ansfering knowledge and employees
spend 7 -20% of their work time replicating existing solutions by others”. And knowledge
represents one of the most important assets for all companies and or ganisations. That means
that any organisation that doesn’t priorit ize knowledge management is headed towards a huge
financial loss. Therefore , the value of a knowledge sharing application comes in the form of
efficiency and productivity and the savings it can produce. All the departments of the
organisation rum more smoothly when the users have immediate access to detailed and
updated information to guide them in their day to day activities.
1.2 Benefits of a Knowledge Sharing Application
Just lo oking at the troubling figures from the paper “The Knowledge Quotient” , you c an
already guess most of the benefits of having a Knowledge Sharing Application. But the
biggest problem the app resolves is the way the information is organized and how it can best
streamline the search experience for every user.
Having your knowledge ba se organi sed inside a knowledge sharing app or a knowledge
management tool helps organisations to have a more efficient and organised team, which
increases the productivity and the profitability of the business. Organisations that use a
knowledge sharing or management tool can have their employees share or access updated
information wherever they are.
Some of the most tangible benefits of using a knowledge sharing app include:
• Employee satisfaction – knowledge sharing applications with gamifications or
rewa rding feature s allow companies and organisations to easily find and reward
employ ees that are leading knowledge contributors and/or assimilators;
• Accurate information – more information accuracy and consistency ;
• Knowledge base – easily and regularly updat ed;

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
5
• Increased content confidence – when the information is regularly updated, the
confusion caused by outdated information or duplicated content is avoided;
• Time optimisation – less time spent searching for information and answers ;
• Fast o n-boarding – controllable and faster on -boarding for new employees ;
• Distribution of knowledge – knowledge that resided only with one individual or, at
most, one department, is now made available across the organisation to benefit
everyone who needs it;
• Easy data discovery – the ability to quickly find the desired data and information,
without losing valuable time searching across multiple apps and spaces;
• Prevent information loss – when team members leave the company or move to a
new position, their information will be avail able to the people that replaces them.

1.3 Difference between Data, Information & Knowledge
When working on a knowledge sharing and management application, you must really
understand the difference between data, information and knowledge. Data is a set of facts,
concepts, statistics that can be analysed and used to produce information. Instead, information consists of data that has been categorised, analyse d and organised to have a
structure and a meaning. Knowledge is a combination of information and data , put in the
context of the user’s experience, expert opinion and acquired skills, resulting in a valuable
asset that helps the user in making decisions.

People always confuse data with information, which usually leads to critical mistakes. Data is alwa ys correct, while information can be wrong. As an example, my age cannot be 36 and 49

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
6
at the same time, but there can exist two different files, one saying that I was born in 1982
and the other stating I was born in 1969.
Considering everything written a bove, knowledge is the most important asset in a company
or an organisation. It’s important that the employees have access to knowledge, not just to the
data. For example, in a company’s sales department, everybody can have access to the sales
figures for a specific client. But just this data is not at all as useful as the knowledge assimilated by the sales agent in charge of the client, that combines the data with the
experience and the skills acquired in time. That’s why it is important that knowledge is easily
and frequently shared and updated, so that anybody that needs to work with that specific client has access to the knowledge. Which will really help to speed up the process and thus
increasing productivity and decreasing the time spent searching for data and information that
otherwise is accessible at the user’s fingertips.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
7
2. Technologies used for this project
As I have specified before, for this project I have chosen to use WordPress as a headless
CMS, using the WP Rest AP I to feed data to the front -end
2.1 WordPress
WordPress is an open- source content management system which is used to power millions of
websi tes and blogs, and an increasing number of web applications. According to the
W3Techs website, which provides infor mation about the usage of various types of
technologies on the web, WordPress currently powers almost 35% of the top 10 million
websites on the Internet (as of May 2019) . And if you limit the data set to only websites with
a known CMS, WordPress’ market sh are gets even more dominant, at 60.7% market share.
It’s usability, extensibility, and mature developer community make it a popular choice for
websites of all sizes.
To look back at the history of WordPress, it’s enough to go to the platform’s official sit e,
which states: “ WordPress started in 2003 when Mike Little and Matt Mullenweg created
a fork of b2/cafelog , which is the basis of Wordp ress as we came to know it in the past 10
years. The need for an elegant, well -architected personal publishing system was clear even
then. Today, WordPress is built on PHP and MySQL, just as b2/cafelog was, and licensed
under the GPLv2.”
The WordPress open source project has evolved in progressive ways over t he years —
supported by a large community of developers, designers, bloggers, and more , working
together to improve the software . WordPress provides the opportunity for anyone to create
and share, from handcrafted personal anecdotes to world- changing movements. People with a
limited tech experience can use it "out of the box", and more tech- savvy folks can customize
it in remarkable ways. And since the WordPress market -share is so big, that means there is a
huge community of users and that many people are already familiar with the interface, which
will reduce the required onboarding time for new users.
Unlike most enterprise CMSs, WordPress is an open source software , meaning that i t can be
used by anyone for free. Open source software benefits from continuous improvement by
anyone in the world, encouraging multiple and diverse approaches and perspectives to
common problems. The open nature of its codebase makes WordPress one of the most –
reviewed pieces of software in the world. WordPress includes com prehensive theme and
plugin APIs, which allow for extreme flexibility. There are currently over 50,000 free plugins
and over 2,500 free themes. And these themes and plugins only scratch t he surface of what’s

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
8
possible with WordPress. With the full flexibili ty of the theme and plugin APIs, WordPress
can integrate with any other software.
2.2 WP Rest API

WordPress is moving towards becoming a fully -fledged application framework, and so it
needed new APIs. An API (Application Program Interface) is a set of pro tocols for building
software applications. It defines the way information is shared between programs and
structures the way different components of an application will interact with each other. A
good API makes for easier program development by providing a ll the necessary pieces.
REST (Representational State Transfer) is an architectural style defining constraints on the
way programs are made. When this architecture is met by web services we called them
RESTful APIs or, simply, REST APIs.
JSON (JavaScript O bject Notation) is a format for structuring data so that a large number of
applications can read it. It makes interactions between something like, say, WordPress, and
any kind of app conv enient.
As of WordPress 4.7, these concepts have been applied to crea te the WordPress JSON REST
API and they were included in the core installation files . It allows for a decoupled approach,
effectively separating data (back) from views (front).
This means that from now on, WordPress can be used as a headless CMS , offering a whole
new world of possibilities for developers, as the frontend of WordPress doesn't need to be
"WordPress" — PHP-generated views. The ever -growing numbers of frontend frameworks
can n ow be hooked up to a WordPress backend to develop websites and applic ations.
By decoupling content management from frontend display, a headless CMS allows
developers to use any technology to display content. Developers are not locked into the
templating en gine provided by the CMS. The CMS might be written in PHP, but developers
working in languages like JavaScript, React, React Native, and Vue.js, can use an API to retrieve, store, and display data. A frontend developer has complete control over the website
or application’s markup and user experience, using clientside technologies to create smooth interactive experiences. It also means that if the frontend needs to be displayed in a new way
(for example a redesign or to display content on a new device) the C MS can still hold the
data, removing the need for complex migrations .

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
9

When you use a headless CMS there are two components: the CMS itself and the frontend
display. By splitting up your website or application in this manner, you can improve
performance and provide a superior user experience. The CMS focuses only on content
management, without having to assemble formatted responses, while the client -side
technology can quickly display that data in the browser. Using client -side technologies fo r
display means that in -browser experiences are fast, acting in real time, without having to wait
for PHP to generate entire pages. There is a significant increase in performance when using
JavaScript vs PHP: Node.js, for example, can handle many more requ ests than PHP due to its
asynchronous event driven nature. This can be especially useful when an application requires
many connections open simultaneously.
With a traditional, monolithic CMS, data is simply displayed by the CMS itself. Data stored
in a headless CMS is available for display in any context. You may want to use it for a
website now, but later you may decide to use the same data for a desktop or touch screen
application. The stored data is always available via the API.
A headless CMS can be used to store all of the data for one site or application, or it can just
be one elem ent of a larger application that retrieves and aggregates data. This means that data
can be integrated into existing workflows as just one layer. For example, it could be use d just
as a layer for translating content which is then pushed to another CMS.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
10

To see exactly how the WP REST API is working, we can go to it’s official page, that states
that “ The WordPress REST API provides an easy -to-use set of HTTP endpoints that l et you
access 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. ”
But how do we get the web site’s posts? Simple, we just send a GET request to mysite.ro /wp-
json/wp/v2/posts . But what if we want to update the user with ID 4? In this case, we send
a POST request to mysite.ro /wp-json/wp/v2/users/4. And if we want to list all the results for
the search term “movie ”, we should sent a GET request to mysite.ro /wp-
json/wp/v2/posts?search= movie . It’s that easy.
The API exposes a simple yet powerf ul interface to WP Query, the posts API, post meta API,
users API, revisions API and many more. Chances are, if you can do something with
WordPress, WP REST API will also let you do it.”

The WordPress REST API is organized around REST and is designed to have predictable,
resource -oriented URLs and to use HTTP response codes to indicate A PI errors. The API
uses built -in HTTP features, like HTTP authentication and HTTP verbs, which can be
understood by off -the-shelf HTTP clients, and supports cross -origin resource sharing to allow
you to interact securely with the API from a client- side web application.
The REST API uses JSON exclusively as the request and response format, including error responses. While the REST API does not completely conform to the HAL standard , it does

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
11
implement HAL’s ._links and ._embedded properties for linking API resources, and is fully
discoverable v ia hyperlinks in the responses.
The REST API provides public data accessible to any client anonymously, as well as private
data only available after authentication . Once authenticated the REST API supports most
content management actions, allowing you to build alternative dashboards for a site, enhance your plugins with more responsive manage ment tools, or build complex single -page
applications. This API reference provides information on the specific endpoints available through the API,
their parameters, and their response data format.
Unlike many other REST APIs, the WordPress REST API is distributed and available
individually on each site that supports it. This means there is no singular API root or base to
contact; instead, we have a discovery process that allows interacting with sites without prior
contact. The API also exposes self -documentation at the index endpoint, or via
an OPTIONS request to any endpoint, allowing human- or machine -discovery of endpoint
capabilities.

Global Parameters
The API includes a number of global parameters (also called “meta -parameters”) which
control how the API handles the request/r esponse handling. These operate at a layer above
the actual resources themselves, and are available on all resources. The API natively supports JSONP
responses to allow cross -domain requests for legacy br owsers and clients.
This parameter takes a JavaScript callback function which will be prepended to the data. This URL can then be loaded via a <script> tag. T he callback function can contain any
alphanumeric, _ (underscore), or . (period) character. Callba cks which contain invalid
characters will receive a HTTP 400 error response, and the callback will not be called.

Pagination
WordPress sites can have a lot of content —far more than you’d want to pull down in a single
request. The API endpoints default t o providing a limited number of items per request, the
same way that a WordPress site will default to 10 posts per page in archive views.
Pagination Parameters

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
12
Any API response which contains multiple resources supports several common query
parameters to handle paging through the response data:
• ?page= : specify the page of results to return.
• For example, /wp/v2/posts?page=2 is the second page of posts results
• By retrieving /wp/v2/posts , then /wp/v2/posts?page=2, and so on, you may access
every available po st through the API, one page at a time.
• ?per_page= : specify the number of records to return in one request, specified as
an integer from 1 to 100.
• For example, /wp/v2/posts?per_page=1 will return only the first post in the
collection
• ?offset= : specify an arbitrary offset at which to start retrieving posts
• For example, /wp/v2/posts?offset=6 will use the default number of posts per
page, but start at the 6th post in the collection
• ?per_page=5&page=4 is equivalent to ?per_page=5&offset=15

In addition to the pagination query parameters detailed above, several other parameters
control the order of the returned results:
• ?order= : control whether results are returned in ascending or descending order
• Valid values are ?order=asc (for ascending order) and ?order=desc (for
descending order).
• All native collections are returned in descending order by default.
• ?orderby= : control the field by which the collection is sorted
• The valid values for orderby will vary depending on the queried resource; for
the /wp/v2/posts collection, the valid values are “date,” “relevance,” “id,”
“include,” “title,” and “slug”
• See the REST API reference for the values supported by other collections
• All collections with dated reso urces default to orderby=date

Linking and Embedding
The WP REST API incorporates hyperlinking throughout the API to allow discoverability
and browsability, as well as embedding related resources together in one response. While the

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
13
REST API does not com pletely conform to the entire HAL standard, it implements
the ._links and ._embedded properties from that standard as described below.

Links
The _links property of the response object contains a map of links to other API resources,
grouped by “relation.” The relation specifies how the linked resource relates to the primary
resource. (Examples include “author,” describing a relationship between a resource and its author, or “wp:term,” describing t he relationship between a post and its tags or categories.)
The relation is either a standardised relation , a URI relation ( like https://api.w.org/ter m) or a
Compact URI relation (like wp:term). (Compact URI relations can be normalised to full URI
relations to ensure full compatibility if required.) This is similar to HTML <link> tags, or <a
rel=""> links.
The links are an obje ct containing a href prope rty with an absolute URL to the resource, as
well as other optional properties. These include content types, disambiguation information,
and data on actions that can be taken with the link.
For collection responses (those that ret urn a list of objects rath er than a top -level object), each
item contains links, and the top- level response includes links via the Link header instead.

Embedding
Optionally, some linked resources may be included in the response to reduce the number of
HTTP requests required. The se resources are “embedded” into the main response.
Embedding is triggered by setting the _embed query parameter on the request. Thi s will then
include embedded resource s under the _embedded key adjacent to the _links key. The layout
of this object mirrors the _links object, but includes the embedded resource in place of the
link properties.
Only links with the embedded flag set to true can be embedded, and _embed will ca use all
embeddable links to be embedded. Only relations containing embedded responses are included in _embedded, however relations with mixed embeddable and unembeddable links
will contain dummy responses for the une mbeddable links to ensure numeric indexe s match
those in _links .

Discovery

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
14
When your client talks to an unknown site, you’ll need to discover what the site is capable of
and how the site is configured. There are a couple of steps for this, depending on what you
need to discover.
Discovering t he API
The first step of connecting to a site is finding out whether the site has the API enabled. Typically, you’ll be working with URLs from user input, so the site you’re accessing could
be anything. The discove ry step lets you verify the API is available, as well as indicating how
to access it.
Link Header
The preferred way to handle discovery is to send a HEAD request to the supplied address.
The REST API automatically adds a Link header to all front -end page s that looks like the
following:
Link: <http://mysite.ro/wp -json/>; rel="https://api.w.org/"

This URL points to the root route ( /) of the API, which is then used for further discovery
steps. For sites without “pretty permalinks” enabled, /wp -json/ isn’t automatically handled by
WordPress. This means that normal/default WordPress permalinks will be used instead. These headers look more like this:

Link: <http://mysite.ro/?rest_route=/>; rel="https://api.w.org/"

Clients should keep this variation in mind and ensure that both routes can be handled
seamlessly. This auto -discovery can be applied to any URL served by a WordPress
installation, so no pre -processing on user input needs to be added. Since this is a HEAD
request, the request should be safe to send blindly to servers without worrying about causing
side-effects.
Element
For clients with a HTML parser, or running in the browser, the equivalent of the Link header is included in the <head> of front -end pages through a <link> element:

<link rel=' https://api.w.org/' href='http://mysite.ro/wp -json/' /

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
15
Authentication
A major challenge around building a REST API is authentication: how does an API know
that a user should be allowed to update content on a site, for example? Who should be
allowed to r etrieve data? Under what conditions? The WordPre ss REST API uses two forms
of authentication:
• Cookie – this is the basic authentication method used in WordPress. When you log
into your dashboard a cookie is set in your browser. This method is only viable when the current user is logged into WordPress a nd that user has the capability to perform
the action requested.
• OAuth – this is the main authentication method used for external clients, i.e. any third –
party site or application that wants to interact with the API. With OAuth, logged in
users can author ise clients to act on their behalf. Clients are issued with OAuth tokens
so they can interact with the API. The REST API uses OAuth 1.0a so that it can be used by all WordPress websites; OAuth 2.0 requires HTTPS but WordPress does not.

In addition, there is a Basic Authentication method for external clients. However, this is only
recommended for development environments as it involves passing your username and
password on every request, and giving your credentials to clients.

Cookie Authentication
Cookie authentication is the standard authentication method included with WordPress. When
you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme
developers need only to have a logged -in user.
However, the REST API includes a technique called nonces to avoid CSRF issues. This
prevents other sites from forcing you to perform actions without ex plicitly intending to do so.
This requires slightly special handli ng for the API.
For developers using the built -in Javascript API, this is handled automatically for you. This is
the recommended way to use the API for plugins and themes. Custom data models can
extend wp.api.models.Base to ensure this is sent correctly fo r any custom requests.
For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest . These can then be p assed to the
API via the _wpnonce data parameter (either POST data or in the query for GET requests), or

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
16
via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0,
turning the request into an unauthenticated request , even if you’re logged into WordPress.
Note: Until recently, most software had spotty support for DELETE requests. For instance,
PHP doesn’t transform the request body of a DELETE request into a super global. As such,
supplying the nonce as a header is the most re liable approach.
It is important to keep in mind that this authentication method relies on WordPress cookies.
As a result this method is only applicable when the REST API is used inside of WordPress
and the current user is logged in. In addition, the curre nt user must have the appropriate
capability to perform the action being performed.

2.2.1 Why use the WordPress REST API
The WordPress REST API makes it easier than ever to use WordPress in new and exciting
ways, such as creating Single Page Applications on top of WordPress. You could c reate a
plugin to provide an entirely new admin experiences for WordPress, or create a brand new interactive front -end experience.
You would not even have to write the applications in PHP: any programming language that
can make HTTP requests and interpret JSON can interact with WordPress through the REST
API, from Node.js to Java and beyond.
The WordPress REST API can also serve as a strong replacement for the admin -ajax API in
core. By using the REST API, you can more easil y structure the way you want to get data
into and out of WordPress. AJAX calls can be greatly simplified by using the REST API,
enabling you to spend less time accessing the data you need and more time creating better
user experiences.
Our imagination is the only limit to what can be done with the WordPress REST API. The
bottom line is, if you want a structured, extensible, and simple way to get data in and out of
WordPress over HTTP, you probably want to use the REST API. For all of its simplicity the
REST API can feel quite complex at first, and we will attempt to break it down into smaller
components so that we can easily piece together the full puzzle.
2.2.2 How does the WordPress REST API work
To get started with using the WordPress REST API we will bre ak down some of the key
concepts and terms associated with the API:
• Routes/Endpoints
• Requests
• Responses

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
17
• Schema
• Controller Classes

Each of these concepts play a crucial role in using and understanding the WordPress REST
API. Let’s briefly break them down s o that we can later expl ore each in greater depth.
Routes & Endpoints
A route, in the context of the WordPress REST API, is a URI which can be mapped to
different HTTP methods. The mapping of an individual HTTP method to a route is known as
an “endpoint” . If we make a GET reque st to http://mysite.ro/wp -json/ , we will get a JSON
response showing us what routes are available, and within each route, what endpoints are available. /wp-json/ is a route itself and when a GET request is made it matches to the
endpoint that displays what is known as the index for the WordPress REST API.

Requests
One of the primary classes in the WordPress REST API infrastructure
is WP_REST_Request . This class is used to store and retrieve information for the current
request; r equests can be submitted remotely via HTTP but may also be made internally from
PHP with WordPress. WP_REST_Request objects are automatically generated for you
whenever you make an HTTP request to a registered route. The data specified in the request will determine what response you get back out of the API. There are a lot of neat things
you can do using the request class

Responses
Responses are the data you get back from the API. The WP_REST_Response class provides
a way to interact with the response da ta returned by endpoints. Responses can return the
desired data, and they can also be used to return errors.

Schema
Each endpoint requires and provides slightly different data structures , and those str uctures are
defined in the API Schema. The schema structures API data and provides a comprehensive
list of all of the properties the API can return and input parameters it can accept. Schema also

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
18
provides security benefits for the API, as it enables us to validate the requests being made to
the API.
Controller Classes
As you can see, the WordPress REST API has a lot of moving parts that all need to work
together. Controller classes bring all of these elements together in a single place. With a
controller class you can manage the registration of routes & endpoints, handle requests,
utilize schema, and generate API responses.

2.3 React JS
React was created by Jordan Walke, a software engineer at Facebook. He was influenced
by XHP , an HTML component framework for PHP . It was first deployed on Facebook's
newsfeed in 2011 and later on Instagram.com in 2012. It was open -sourced at JSConf US in
May 2013. React Native, which enables native Android, iOS , and UWP development with
React, was announced at Facebook's React.js Conf in February 2015 and open- sourced in
March 2015. On April 18, 2017, Facebook announced React Fiber , a new core algorithm of
React framework library for building user interfaces . React Fiber will become the foundation
of any future improvements and feature development of the React framework.
React does not attempt to provide a complete 'application framework'. It is aimed squarely at
building user interfaces, and therefore does not include many of the tools some developers
consider necessary to build an application. This allows the choice of whichever libraries the
developer prefers to accomplish tasks such as performing network access or local data
storage. Common patterns of usa ge have emerged as the library matures.
To support React's concept of unidirectional data flow, the Flux architecture represents an
alternative to the popular Model -view -controller architecture. Flux features actions which are
sent through a central dispatcher to a store , and changes to the store are propagated back to
the view]. When used with React, this propagation is accomplished through component
properties. Flux can be considered a variant of the observer pattern .
A React component under the Flux architecture should not directly modify any props passed
to it, but should be passed callback functions that create actions which are sent by the
dispatcher to modify the store. The action is an object whose responsibility is to describe
what has taken place: for example, an action describing one user 'following' anot her might
contain a user id, a target user id, and the type USER_FOLLOWED_ANOTHER_USER .

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
19
The stores (which can be thought of as models) can alter themselves in response to actions
received from the dispatcher.
This pattern is sometimes expressed as "propert ies flow down, actions flow up". Many
implementations of Flux have been created since its inception, perhaps the most well -known
being Redux which feat ures a single store, often called a single source of truth.
React Native was announced by Facebook in 2015, applying the React architecture to
native Android, iOS and UWP (Universal Windows Platform) applications. In 2012 Mark
Zuckerberg commented, " The biggest mistake we made as a company was betting too much
on HTML5 as opposed to native ". He promised that Facebook would soon deliver a better
mobile experience.
It can be seen that Facebook corrected the error that Mark Zuckerberg mentioned in 2012,
mentioned above. React Native doesn't rely on HTML5 at all, everything is written in
JavaScript, an d relies on native SDKs.

Why React JS?
WordPress REST API makes it easier to connect to apps. A custom looking mobile app can
now more easily than ever not only read WordPress data, but also create, edit and delete that
data. Many have started to use Word Press in "weird places", as in applicatio ns where it would
have been a pain to work with a few years ago. As for me? I chose React for this project because it is still one of the best frameworks out there: flexible & reusable component
system, Facebook- backed open source project, efficient workfl ow with JSX, to name just a
few of its advantages.
With the front -end world changing on a daily basis, it’s hard to devote time to learning a new
framework – especially when that framework could ultimately become a dead end. So, after
thoroughly considera ting all the pros and cons, I have chosen to use React for the web
interface portion of the application (and consider using React Native for the mobile apps that
will follow at some point). Below I have listed some of the reasons that led me to choose
React.js:
• Simplicity
ReactJS is just simpler to grasp right away. The component -based approach, well -defined
lifecycle, and use of just plain JavaScript make React very simple to learn, build a
professional web (and mobile applications), and support it.
• Easy to learn

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
20
Anyone w ith a basic previous knowledge in programming can easily understand React while
Angular and Ember are referred to as ‘Domain specific Language’, implying that it is
difficult to learn them. For reac t you just need basic knowledge of CSS and HTML.
• Native Ap proach
React can be used to create mobile applications (React Native). And React is a diehard fan of
reusability, meaning extensive code reusability is supported. So at the same time we can
make IOS , Android and Web application.
• Data Binding
React uses one -way data binding and an application architecture called Flux controls the flow
of data to components through one control point – the dispatcher. It's easier to debug self –
contained components of la rge ReactJS apps.
• Performance
React does not offer any concept of a built -in container for dependency. You can use
Browserify, Require JS, EcmaScript 6 modules which we can use via Babel, ReactJS -di to
inject dependencies automatically.
• Testability
ReactJS applications are super easy to test. React views can b e treated as functions of the
state, so we can manipulate with state we pass to the ReactJS view and take a look at the
output and triggered actions, events, functions, etc.

2.4 How Will It All Work Together
By using WordPress as a Headless CMS using the WP Rest API, we can easily use the same
Wordpress Admin Panel for all instances of the application, being the web app or the native
mobile apps. By doing so, we are transforming WordPress from the cla ssic blogging CMS
everybody knows into a fully -fledged application framework. WP Rest API provides an easy
way for external programs to communicate with the WordPress database, so all our
applications (web and mobile) will have the data kept in the same WordPress database.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
21

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
22
3. Knowledge Sharing App – A WP Rest API & React.js Web Application

The graduation/dissertation paper should respect, by and large, the structure of a scientific
paper. Apart from a theoretical first chapter that introduces the general and specific concep ts
of the paper, this implies including a chapter in which to set and describe in detail the
methodology of the study that the paper is based on and a chapter that interprets and
discusses these results.
3.1. About the application and it’s use cases
As I have previously mentioned in this paper, I have chosen the approach to build my web
app with WordPress as a Headless CMS , the WP Rest API and React.js due in majority to the
fact that I have previously worked exten sively with WordPress and I recently started making
some experience with the WP Rest API. As to why I chose to use React.js for the app interface, the simple expl anation is that React can be used to create both the interface of the
web app and mobile appli cations (through React Native), which will be the next step in
developing and expanding this application. And this solution works best if what you are
building is a SaaS (Software as a Service) Web Application.
The application presented here is not in any case the most complex knowledge sharing
application on the market, but instead is simple and it is built to do what is necessary: to help
people and teams to sha re their accumulated knowledge with everybody or at least with their
teammates. The applicatio n has the basic components needed to make this work: A login
page, a page for the available courses /articles , a page for the single course view, the page for
adding new courses and the profile administration page, which allows the user to control the
settings of his/her profile. I’ll detail every page going forward.
The application will be accessible via an user account. If you don’t have an account, you won’t be able to see any of the articles. There are two types of user accounts that will be
accessible. The first one is the Basic User that has a ver y basic set of skills. The Basic User
can log into his/her user account and see the available articles. If the user is not part of any
UserGroup, the only articles visible will be the General Available Article s, the articles that
are visible to all users that are logged to their account. We have below a Use Case diagram
for the Basic User.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
23

The Advanced user has the skills of the Basic User, but with some extra features. Besides the
Basic User Skills, the Ad vanced User has a role of a User Group manager. He/she has the
ability to create a User Group and to add other users to this User Group. All the users that are
part of the User Group have the ability to see the articles available only to the Group,
additio nally to the General Available Articles. More, they can add new articles to be available
to the members of his/her User Group. The article will not be published immediatly, but
rather will be in a state of pending until it is approved/published by the Use r Group Manager .
While doing this, the Advanced user can set the right to the article, if it will be visible to everybody, thus setting the article as a General A vailable Article, or if it will be visible only
to the User Group members, thus setting the ar ticle as a Privately Available Article.
So the Advanced User has the ability to add users to the Ser Group and to delete users from
the User Group. More, he/she c an see statistics about the users from the User Groups.
Available statistics are: the number o f articles published, the number of articles viewed, the
number of articles completed and a percentage of completed articles from all viewed articles.
Every article has a quiz at the end, to the test the knowledge assimilated from the article by
the user. In the statistics page, the Advanced User can see a procentage of succeeded quizes
from the total number of completed articles. We can see below a use case diagram for the
Advanced User:

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
24

Based on the use cases presented above, the application will consis t from the following
pages:
3.1.1 Login page
The first page of the application the users sees when accessing the app is the Login page. This
will be a standard Login page, with Username and Password fields for the users to
authenticate to the application. The user will also have the option to login with Facebook or Google accounts. For now, the user account swill be crated by an admin, access being
avail able by invitation only. Later, we will have a „ Don’t have an account? Registere here”
message in the log in page and a Register Account page.
The authentication is done by Oauth 2.0. OAuth 2.0 is the industry -standard protocol for
authorization. OAuth 2.0 supersedes the work done on the original OAuth protocol created in
2006. OAuth 2.0 focuses on client developer simplicity while providing specific
authorization flows for web applications, desktop applications, mobile phones, and living
room devices.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
25
3.1.2 Dashboard/User Profile page
3.1.3 Available Articles page
This page contains the basic information a us er should see on a knowledge platform after
logging in his/her account. It has a navigation menu which can be used to switch between
several categories of the articles. If the user is a member of a User Group the he/she shall see
the General Available Arti cles and the Privately Available Articles tagged for the respective
User Group. If the user is not yet part of any User Group he/she will only see the list of the
General Available Articles.
There is a navigation menu displayed which can be used to add a new article in the case of
the Basic User attached to a User Group or to add a new article and to see users from User
Group for an Advanced User.
3.1.4 Single Article page
This page is the basic page for a single article view. It displays all the information authored in
the article. It ends with a quiz that must be resolved by the user after assimilating the
information. After completing the quiz, the page shows the result of the Quiz: SUCCES or
HAVE ANOTHER TRY.
3.1.5 Add New Article page
This is the page for adding a new article. This will be available for the Advanced User and
for the Basic User, if the user is a member of a User Group. This page will be very similar in
structure to an Add New Article page from WordPress, the main differe nce being that i t will
have some extra fields, added with the Advanced Custom Fields plkugin from WordPress.
The final part of the article should consist of a quiz. The user cannot save the new article if
he/she hasn’t provided a quiz fot the article.
3.1.6 Review Articl e page
This page is basically the page where the Advanced User can review the unpublished articled
from his User Group, before publishing the article. It is basically an Edit Article type page,
where the Advanced User can review, edit, change information a nd content before publishing
an article.
3.1.7 User Statistics page
This page show the Advanced User the statistics fot the user he has selected from the members of the User Group. Here he/she can see the number of articles the user has
published, the number of articles the user has viewed, the number of articles completed and a
percentage of completed articles from all viewed articles. Every article has a quiz at the end,
to the test the knowledge assimilated from the article by the use r. To complete an article, the

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
26
user must complete the quiz at the end of the article. In the statistics page, the Advanced User
can see a procentage of succeeded quizes from the total number of completed articles.

3.2. Designing the system
Having using WordPress as a sol ution for the backend and React.js for the web application
interface, the design of the system is broken in two parts. For the backend we use a basic WordPress installation that will consist of the backend for our application, but w ill also serve
as a separate basic website, that will showcase the application. The website will have all the necessary information about the application, like „Why to use”, „How to use” , „Pricing” or
„FAQ”, and of course a link to the web app Login page.
Besides the basic Wordp ress installation, I have created a custom WordPress plugin that
creates the custom post type that will be used for the articles, the custom fields used for the previously mentioned custom type and the roles of the users we need for the application.
For t he interface I will use a simple React.js app that will take the information from the
Wordpress backend through the WP Rest API. The React app will have a page template setup for every page I have previously mentioned in this paper , with components created for every
part of every page .
3.3. Implementing the solution
So, to implement the solution, we will be working in two phases. In Phase One, we will
implement the back -end using WordPress as a Headless CMS, while in Phase Two we will
implement the front -end using the ReactJS library .
Phase One – Back-end
The core of the application is a standard WordPress website, so the first thing we need is a
standard WordPress install. The first thing I did after installing WordPress was to install two
authentication plugins, so users could be authenticated through the REST API. The first one
is Basic -Auth. It introduces simple user name password authentication to the REST API. This
will be used just for development and debugging purposes, as it basically strips away any
authentication layer and allows anyone to log in using just the username and password. But
because we can log in through just a username and password, it's very useful when we
work with a local developme nt environment where we need to constantly authe nticate and re –
authenticate everything. The second installed plugin is WP OAuth Server Pro, which I'll be
using on the live site to authenticate through OAuth 2.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
27
Next, I created a new custom plugin, that extends the out of the box functionality of
WordPre ss to include an Article custom post type, some new custom fields, and a new user
role. Inside the WordPress installation folder, inside /wp- content/plugins/ I c reated a new
folder called Learning and inside that folder I created a new file called learnin g.php.
The plugin needs its own custom post type called Learn that we can attach custom fields ,
custom user roles to, and also store the Learn items in. In the Learning folder, I created a new
folder, call ed it Includes and inside created a file nam ed posttypes .php. This file holds all the
custom post type code and nothing else , being separate for ease of access purpose. For the
plugin to be aware of this new file, I added a new statement at the top of the learning.php file,
using the require_once statement .

With the function plugin_dir_path, we grab the current file, learning .php, and use it to find
out which plugin directory we're currently sitting in, which is the Learning directory. That is
returned, and then I just say, ‘ includes/posttypes.php’ and when learning .php
runs, posttypes.php also runs.
Now it ’s time to set up the c ustom post type itself.
Now we can set up the custom post type itself. The easiest way to do that is to go
to developer.wordpress.org and search for Register Post Type. This function is what
registers custom post types, and here if you scrol l down a bit, you'll find some
examples. And you're looking for this one, the one that's currently number
nine, contributed two years ago. If you expand the full source code, you'll see this is
the code to register a custom post type called book, and it has all the necessary
code in it already. So if you copy this code, verbatim, paste it in to
posttypes.php, then you get a new custom post type called Books.
But that's not what we want. We want a custom post type called Task. So we'll do a
simple Search Replace for all the strings here. And first I'll search for Book, replace it
with Task. So you see here we have both singular and plurals, so this will replace all
Book or Books with Task or Tasks. Then I also need to replace the textdomai n. This
is used anyt ime someone wants to translate the plugin, so textdomain is generic,
that's not what I want. Instead, I want the textdomain for my plugin, which you'll
remember is taskbook.
We defined it here in the header for the plugin. So I'll put t hat in here, and cli ck
Replace All. And now the end result is all our text strings say Task or Tasks and
these text strings are translatable for the plugin. The next step is to change the name
of the function itself. You can see right now it's called wpdoc s_codex_Task_init, so
I'm going to change this to taskbook_cpt_init. This function is called using an action

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
28
at the very bottom, so here we add an action at initialize, and the callback will be our
new custom post type function, taskbook_cpt_init.
Okay, th at does away with labels and the function itself, and now we can focus on
setting up the custom post type. The task custom post type is a little bit different than
normal custom post types because we only want it to be available through the third
party app. So the external app, not through the WordPress site. Meaning, if you go to
the front end of the WordPress site, you should never see any of the tasks. To
accomplish this, I'll set public and publicly_queryable to false.
Doing this means the tasks and the task post type will be available on the back end
of WordPress, but if you try to gain access to any of the tasks on the front end you
simply get a 404 page. It also means if you do a search on the WordPress site for
any content, you'll never come across any of the tasks, which is exactly what we
want. That also means technically we don't need this rewrite array slug task
anymore, but I'm going to leave it in, just change it to say tasks, with a lowercase t in
case in the future you may want to publish the task for some reason .
But it sits there and there won't be any errors. We'll leave capability_type to the next
movie 'cause we're going to do something custom here, and instead scroll a little
further down. Under hierarchical, you can place it anywhere, but I like to place it
under hierarchical, I'm going to add a new property, show_in_rest. This allows us to
gain access to the custom post type through the REST API, so I'll set that to
true. And then I'll set up another one called rest_base and this gives us the base for
the R EST API route.
And in our case, that should be tasks. That means if we go to the REST API and
request tasks, we get this custom post type. To customize the custom post type a
little bit further in WordPress Admin, I also want to add a m enu icon, so under
menu_position I'll say menu_icon. And then I'll go to the dash accounts
resource, under developer resources. Here you can pick any of the existing icons
within WordPress. So I pick this one called dashicons -excerpts -view.
I'll copy out t he class name that y ou see here. Put it in comments, and then finally in
the arguments array, I want to change what is currentlysupported by this post
type. You can see this post type supports everything, but all I need for tasks is title,
editor, and author, so I'll just rem ove the rest. All that's left now is to register the
custom post type, and here we give it the machine- readable names. This is how
we're going to refer to the custom post type in all our code in the future.
And here again, I'm just going to call it task with all lowercase so that everything
works properly and there's no accidental upper -lowercase mess. Save
posttype.php. Go back to your WordPress site and reload admin, and if everything
works correctly, you'll now have a new option in th e main menu here cal led
Tasks, from which you can see all tasks or add new tasks. If you go to add new
tasks, you'll see here we havetitle, content, and author, nothing else.
And that's exactly what we want.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
29
Phase Two – Front-End

On the whole, the size of the bachelor / dissertation paper should be between 40- 70
pages (excluding the abbreviations, table / chart lists, introduction, conclusions, bibliography
and annexes).
The following chapters 3, 4, …

3.4. Class Diagram

3.5. Activity Diagram
Considering the main activities that can be done by the two types of users, I have created
below the activity diagrams for these activities.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
30
3.5.1 Manage Article Activity Diagram
There are two types of activities a user can do while logged in this web applicatio n. The first
one can be done by both Basic User and Advanced User and it is the manage articles activity.
The diagram below is about the articles added by the logged in user and what options the user
has to control these articles besides to view the article. The user can choose right from the
start to add a new article or to access an article that already exists. If he/she creates a new article, the user can add the needed information to the article. After that, the user m ust assign
a category to the articl e and save it. Later, the Advanced user will assign the availability of
the article and then publish it.
If an article exists, then there are two options: the article can either be modified or deleted. Any user can modif y it’s own created articles, but th e modifications will only be published
after the Advanced User approves them. An article can only be deleted by the Advanced User.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
31
3.5.2 Manage User Activity Diagram
The users in the User Group are managed by the Advanced User. The Advanced User has
two main options: he can add a new user to the User Group or he can delete an existing user
from the Usre Group. If a user is not in the User Group, the Advanced User will add that user to the User Group and then return to the users management page.
If a use r is in group, the Advanced User has two options. He/she can remove the user from
the User Group or go to the user’s statistics page. If the user is removed, the Advanced User
is returned to the Management Users page. If the Advanced User chooses to see th e statistics
os the user, he is redirected to the User Statistics page. From here, the Advanced User can
either go back to the Users Management page or he can exit the application.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
32

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
33
3.6. Collaboration Diagram
The diagram showed below was created taking into consideration the communicatuons
between different objects used during the client interaction with the paltform.
First, the user is accesing the site and by doing so he sees the web interface created in
React.js. The content of the web page is fetche d from the WordPress database through the
WP Rest API, so the user has access to the list of available articles and the details for every article in the list. The articles are fetched from the WordPress database through the WP Rest
API and delivered in a JSON format, whioch is then read and translated into the web page
content of the user’s client, web or mobile application.

3.7. Co mponents Diagram
The below diagram illustrates the main components of the ap plication and the relation
between them. There are two major components: User Interface and Administration Interface, each of them containing a set of subcomponents.
User interface comprises the Available Articles component that is interacting with the Single Article component that is related with the Quiz Component. These three components are
linked between them in this order and depend on each other to finalize an eligible order.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
34
The second main component, Administration Interface, contains three subcomponents: Login,
Administration and Statistic. In order to access the Administration and Statistics part of the
platform the login is compulsory otherwise those sections of the Administration interface cannot be accessed.

3.8. Exploatation Diagram

The exploitation diagram below presents the configura tion of the exempts during the
processing from the execution time and the components contained.
The two main components presented in detail in the Components Diagram section are linked
through the proc ess of altering -updating the data. Any update that wil l be made by the
administration will be visible in the User Interface.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
35

3.9. Sequence Diagram

The most important important part of this Knowledge Sharing web applications is the userțs
ability to navigate througfh the available articles, to read the art icles and, of course, to
complete the quiz at the end of every article.
In the diagram below, I have structured the logical flow, based on the type of the user. We
see in the diagram below the Premium User/Advanced User has the ability to add/remove users from the User Group.
The Basic User at first is required to authenticate to the application. Th en, he sees the articles
that are available for the User Group that he is a part of. He has also the ability to add a new article. When accessing a new article page, the user can read and assimilate all the
information in the article and complete the quiz at the end of the article.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
36

3.10. Data Base View
The database used for this project contains the usual tables created during a standard
Wordpress instalation. The newly created custom post types (articles) will be stored in the wp_post table, while the custom fields are stores into the wp_term_taxonomy table. We will
also have additional tables due to the using of OAuth 2.0 solution for authentification. Below you can see the database diagram.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
37

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
38
4. Testing the application

(blank line, 12pt, 1.5 spacing , no space before and after paragraph)
(blank line, 12pt, 1.5 spacing, no space before and after paragraph)
(blank line, 12pt, 1.5 spacing, no space before and after paragraph)
The graduation/dissertation paper should respect, by and large, the structure o f a scientific
paper. Apart from a theoretical first chapter that introduces the general and specific concepts
of the paper, this implies including a chapter in which to set and describe in detail the
methodology of the study that the paper is based on and a chapter that interprets and
discusses these results.
4.1. What is web testing
Web Testing in simple terms is checking your web application for potential bugs before its
made live or before code is moved into the production environment.
During thi s stage issues such as that of web application security, the functioning of the site,
its access to handicapped as well as regular users and its ability to handle traffic is checked.
I broke the testing for the web application in 5 different steps:
• Testing the wo rdpress installation and the newly created custom plugin
• Testing the API endpoints with Postman
• Manual functional & visual testing
• Accesability testing
• Automated re gression tests.

4.2. Testing WordPress and the custom plugin
This part of the testing take s place after the WordPress installation is all set up and before the
React.js web interface is set. At this point we are making sure that everything we prepared in
Wordpress is et up properly, so that we can get to testing the API endpoints and then setti ng
up the web interface. We will be testing the custom plugin that create the custom post type, custom fields for the custom post type and the user roles needed for our application. This
testing will be performed manually, based on the basic p ost type tes ting in WordPress.
First, I created a new custom post from the WordPress admin for two different users, setting them to „Private” just as you would set any standard WordPress post and then check for each
of the users that on the custom posts (a rticles) sec tion, they can only see their own article.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
39

4.3. Testing the API endpoints with Postman
API testing is different from GUI testing as testers don't have a web page to send the
request.So they need a tool to create the request which can be sent to REST ser ver. API
testing tools, in general, provide an interface where client request can be created by adding
whatever goes in the request when provoked through GUI. Some of the elements are URI,
header and method specification.
Postman is a REST API client that is used for mainly testing and building REST clients.
POSTMAN allows you to easily test almost any API with little setup.
To create a new Post from the API we need to do an authenticated request. For this testing I
used Basic Authentication but is important to note that this method is only used for
development and testing purposes, in production I will use OAuth, a more secure
authentication.
A resource is a data object that can be accessed via a HTTP request. The WP REST API
allows you to “access your WordPress site’s data (resources) through an easy -to-use HTTP
REST API”. In the case of the most recent version of the WP API (version 2), the res ources
include the followi ng 9 WordPress objects:
• Posts
• Pages
• Media
• Post meta
• Post revisions
• Comments
• Taxonomies
• Terms
• Users

With the WP API, you can perform any of the four CRUD actions against any of your
WordPress site’s resources listed above. For example, you can use the WP A PI to create a
post, retrieve a post, update a post or delete a post associated with your WordPress website.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
40
It’s important to know that some HTTP requests don’t require authentication (anyone can
make requests and the correspo nding responses). In WP API, for example, certain GET
requests like getting posts and getting media don’t require authentication. Other GET
requests do require authentication though. In our case, we will need authentication as the
custom posts we want to r etrieve are marked as private and only the authenticated author sees
them. As I ’ve mentioned above, only for testing purposes, we will use the Basic
Authentication plugin instead of the OAuth 2.0 solution.
Using Basic Authetication in Postman I checked th e WP Rest API endpoints that it fetches
the correct information in JSON format, considering the user that is authenticated.
4.4. Manual functional & visual testing
4.5. Automated regression testing
Fort the testing of the web interface, I have written a small page- object framework, using
Python and Selenium. The test cases from the automated tests will be run every time new
code is pushed to the application, testing thus that it is still functioning properly.
When you write tests against a web application, you simply simulate user a ctions like click
on element and determine what’s displayed. In the test code you need to refer to elements
within a web pages of that application in order to perform or s imulate user actions. In other
words within your web application there are pages or a reas that your tests interact with.
A page object simply models these as objects within the test code. For each web page of the
web application we can create a correspondi ng class to encapsulate the mechanics required to
perform some action on that page. W e can think about page objects like they represent the
services offered by a particular page and hide the details and mechanics of the page.
For now, the automation framew ork has the following tests added (only positive scenarios):
• login with correct username and password (Basic User)
• add new article
• see available articles
• login with correct username and password (Advanced User)
• add new user to group

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
41
• delete user from group
• add new article
• see available articles
• see unpublished articles .

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
42
Conclusions
Durin g the last three years, I had the opportunity to learn from great teachers and mentors and
to study and work side by side with good colleagues and friends of mine. All this implied
undertaking a great volume of work, putting in a huge amount of effort hopi ng that at the end
of my academic journey I will be a better professional and nevertheless a better person. Following the increasing performance at my working place and the amount of knowledge I
accumulated, I consider that all of this was after all, time and effort good invested for my
present and future development.
By choosing this subject for my paper, I intended to use the knowledge accumulated in the
past three years and acquire some new knowledge while doing so. And while doing this, I
struggled to better under stand the mechanisms of working with APIs and using a headless
CMS. Even though working with WordPress and php wasn’ t new for me, it was still a
struggle to cover everything necessary for this paper in such a short amount of time.
Especially con sidering th at I have also used a platform entirely new for me: React.js.
Even though at first sight this web application could seem rather simple, considering that it is based on the WordPress platform, when looking more thoroughly we can see that it is a rather
complex application. This is why I chose to include in the previous chapters all the relevant
information about the scope of the application, it’s use cases and all the platforms used in
developing this application. Every diagram presented above w ould help a ny reader to
comprehend the structure, the design and the implementation of the application.
Even though this application is developed as a starting point for a startup that will offer
Knowledge Sharing options as SaaS, this is only the first ve rsion of the application, which
has still a few steps of development and grow in front of it. For future development of the application, first I would try to build iOS and Andriod native apps using React Native. The
objective is to have this application be multi- platform, so the user can access the available
articles via web application for desktop or mobile application for smartphones, helping him/her in this way to acquire new knowledge any time, being that he/she is on the bus, train
or waiting his/her turn at the doctor’s office.
Finally I would like to end this paper by officially addressing a big “Thank you” to all my faculty teachers and mentors, for guiding me along this three year journey hoping that we will
have the chance to work and collaborate again, mayb e even sooner than expected at a master
program.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
43
Bibliography

Olink , M. and Jackson Armitage, R . (2011 ), The WordPress Anthology , SitePoint Pty. Ltd. , Australia .
Stellman , A. and Greene, J. (2015 ), Learning Agile , O’Reilly Media, USA.
bin Uzay r, S. ( 2016), Learning WordPress REST API , Packt Publishing, Birmingham, UK.
Acu, I.M. (1996), Title of the book title of the book title of the book title of the book title of the book
title of the book title of the book , Kyz Publishing House, Brașov. // book w ith 1 author
Albulescu, M. and Cocea, N. (2014), Title of the book title of the book the title of the book the title of
the book the title of the book the title of the book the title of the book , Xyz Publishing House,
Bucharest. // book with 2 authors
Bal, N.G., Cornea, I. and Albu, G. (2005), title of the book title of the book title of the book title of the
book title of the book title of the book, Vyz Publishing House, Iași. // book with 3 authors
Cornea, I. and Albu, G. (2007), Title of the specialized article, Journal name , 40 (volume number),
pp. 25- 42. // article with 2 authors
Harvey, C.R. and Liu, Y. (2014), Evaluating trading strategies, Working paper. Available on SSRN:
http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2474755
// article "working pa per"

https://www.w3.org/wiki/Accessibility_testing
*** D ăianu, D., The Eurozone crisis and the geopolitical crisis brake the "New Europe",
http://www.zf.ro/zf -24/criza -zonei -euro-si-cea-geopolitica -franceaza- nua-europa -13684478 .
// press article
*** National Bank of Romania (2012), Annual Report 2011, Statistics Division. // institutions
materials
*** National Institute of Statistics, Consumer Price Index. // data
Remarks:
Bibliographic references are alphabetically sorted (A -Z), after the first author's name. This main set
usually consists of books, scientific papers, papers delivered at conferences but unpublished (working
papers). There is no need to report the references by category (separately on b ooks, articles). It is
recommended that non- standard references (web addresses, unpublished materials, brochures,
specialty articles, rul es, regulations, laws, etc.) form a second set of references immediately after the
main one (with the *** mark). Mandat ory: each source cited in the text of the paper should be found
in the bibliographic reference list and vice versa. There is no optimal number of resources attached to
a work (this depends on the subject, topic, level), but it is advisable to avoid extremes (below 5- 10
references, over 30). The focus should be on articles published in specialized journals (at least 50 %
of referenc es). Indicative restrictions: books (max. 35%), articles published in conference volumes (up
to 10%), unpublished items (max 5%) .

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
44
Annexes

Annex/ Appendix 1. Creating a new WP plugin – learning. php
<?php
/*
Plugin Name: Learning
Plugin URI: https ://facemfilm.ro
Description: Knowledge sharing with courses build as cards
Version: 0.1
Author: Cosmin Milchis
Author URI: https://linkedin.com/in/cosminmilchis/
Text Domain: learning
Domain Path: /languages
License: GPL3

Learning is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.

Learning is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Learning. If not, see https://www.gnu.org/licenses/gpl- 3.0.en.html.
*/

/**
* Register Learn Post type.
*/
require_once plugin_dir_path( __FILE__ ) . 'includes/posttypes.php';
register_activation_hook( __FILE__, 'learning_rewrite_flush' );

/**
* Register Learning Logger role.
*/
require_once plugin_dir_path( __FILE__ ) . 'includes/roles.php';
register_activation_hook( __FILE__, 'learning_register_role' );
register_deactivation_hook( __FILE__, 'learning_remove_role' );

// Add capabilities
register_activation_hook( __FILE__, 'learning_add_capabilities' );
register_deactivation_hook( __FILE__, 'learning_remove_capabilities' );

/**
* Register course status.
*/
require_once plugin_dir_path( __FILE__ ) . 'includes/status.php';

/**
* Add in CMB2 for new fields.
*/
require_once plugin_dir_path( __FILE__ ) . 'includes/CMB2- functions.php';

/**
* Grant course access for index pages for certain users.
*/
add_action( 'pre_get_posts', 'learning_grant_access' );

function learning_grant_access( $query ) {
// Make sure the query contains a post_type query_var,
// otherwise it's definitely not a request for Course(s):
if ( isset($query->query_vars[ 'post_type']) ) {
// Check if the request is for the Course post type…
if ( $query->query_vars[ 'post_type'] == 'course' ) {
// … and that this is a REST request:
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
if ( current_user_can( 'editor' ) || current_user_can( 'administrator') ) {
// If so, Editors and Administrators see all private courses…
$query- >set( 'post_status', 'private' );
} elseif ( current_user_can( 'course_logger' ) ) {
// … and Courses Loggers see only their own courses:
$query- >set( 'post_status', 'private' );
$query- >set( 'author', get_current_user_id() );
}
}

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
45
}
}
}


Annex/Appendix 2. Adding a custom post type – posttype.php
<?php
/**
* Register a custom post type called "learn".
*
* @see get_post_type_labels() for label keys.
*/
function learning_cpt_init() {
$labels = array(
'name' => _x( 'courses', 'Post type general name', 'learning' ),
'singular_name' => _x( 'course', 'Post type singular name', 'learning' ),
'menu_name' => _x( 'courses', 'Admin Menu text', 'learning' ),
'name_admin_bar' => _x( 'course', 'Add New on Toolbar', 'learning' ),
'add_new' => __( 'Add New', 'learning' ),
'add_new_item' => __( 'Add New course', 'learning' ),
'new_item' => __( 'New course', 'learning' ),
'edit_item' => __( 'Edit course', 'learning' ),
'view_item' => __( 'View course', 'learning' ),
'all_items' => __( 'All courses', 'learning' ),
'search_items' => __( 'Search courses', 'learning' ),
'parent_item_colon' => __( 'Parent courses:', 'learning' ),
'not_found' => __( 'No courses found.', 'learning' ),
'not_found_in_trash' => __( 'No courses found in Trash.', 'learning' ),
'featured_image' => _x( 'course Cover Image', 'Overrides the “Featured Image” phrase for
this post type. Added in 4.3', 'learning' ),
'set_featured_image' => _x( 'Set cover image', 'Overrides the “Set featured image” phrase for
this post type. Added in 4.3', 'learning' ),
'remove_featured_image' => _x( 'Remove cover image', 'Overrides the “Remove featured image” phrase
for this post type. Added in 4.3', 'learning' ),
'use_featured_image' => _x( 'Use as cover image', 'Overrides the “Use as featured image” phrase
for this post type. Added in 4.3', 'learning' ),
'archives' => _x( 'course archives', 'The post type archive label used in nav menus.
Default “Post Archives”. Added in 4.4', 'learning' ),
'insert_into_item' => _x( 'Insert into course', 'Overrides the “Insert into post”/”Insert into
page” phrase (used when inserting media into a post). Added in 4.4', 'learning' ),
'uploaded_to_this_item' => _x( 'Uploaded to this course', 'Overrides the “Uploaded to this
post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4',
'learning' ),
'filter_items_list' => _x( 'Filter courses list', 'Screen reader text for the filter links
heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4',
'learning' ),
'items_list_navigation' => _x( 'courses list navigation', 'Screen reader text for the pagination
heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in
4.4', 'learning' ),
'items_list' => _x( 'courses list', 'Screen reader text for the items list heading on
the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'learning' ),
);

$args = array(
'labels' => $labels,
'public' => false,
'publicly_queryable' => false,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'courses' ),
'capability_type' => 'course',
'has_archive' => true,
'hierarchical' => false,
'show_in_rest' => true,
'rest_base' => 'courses',
'menu_position' => null,
'menu_icon' => 'dashicons- exerpt-view',
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
'map_meta_cap' => true,
);

register_post_type( 'course', $args );
}

add_action( 'init', 'learning_cpt_init' );

/**
* Flush rewrite rules on activation.

IMPLEMENTING A KNOWLEDGE SHARING WEB APP USING WP REST AP & REACT JS
46
*/
function learning_rewrite_flush( ) {
learning_cpt_init();
flush_rewrite_rules();
}

Remarks:
The a nnex section may have a maximum size of 20% of the volume of the work (Introduction-
Bibliography). Each appendix (table, figure, data, documents, etc.) must have a title and be numbered.

Similar Posts