WordPress REST API – Part 2

Standard

This post follows on from a previous post, espousing the virtues of the WordPress REST API for hybrid mobile app development.

ionic-and-wordpress

At the 2016 WordCamp in Belfast, I gave a talk about using the WordPress REST API for mobile development. I gave two code walk throughs at the conference; what follows is a walk through of the football mobile app.

The football app uses Ionic to create a cross platform mobile app that:

  • Connects to a remote, REST API enabled, WordPress site.
  • Authenticates a username and password from the device (using JWT – JSON Web Tokens).
  • Shows a ‘Result’ screen. The screen allows users to input a score and match report.
  • Posts this ‘Result’ to the remote WordPress site.

N.B. All the Ionic 1 code is available on Github. There is also an Ionic 3 code repo available here.

The steps to create a shiny new mobile app, which allows soccer coaches to post match results from their phones, is as follows:

Ionic 3 to WordPress

Ionic 3 to WordPress

WordPress Site

We need to first create a WordPress website which will act as our back end engine to our app.

*Also on some servers you will need to enable http auth in your .htaccess file

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

Mobile App

  • Install Node on your machine.
  • Install Ionic and Cordova using the following NPM command/cmd:
    npm install -g cordova ionic
  • Download the github code (cd to the folder you want to put it in first)
    git clone https://github.com/conorw/wp-rest-api-ionic.git

    Or for Ionic 3

    git clone https://github.com/conorw/wp-rest-api-ionic2.git
  • Using the command line navigate (cd) into the created directory
cd wp-rest-api-ionic
  • Get node to install Install the projects dependencies
npm install
  • Change the ionic.config.json file to point to the URL of your new WordPress site
    {
     "name": "teamthingmobile",
     "app_id": "",
     "proxies": [
     {
     "path": "/server",
     "proxyUrl": "https://thenameofyoursite.com"
     }
     ]
    }
  • Start Ionic to show a web verison of your app
    ionic serve

    Done!

    You should now have a working mobile app, executing in your browser, which you can now use your WordPress credentials to login.

If not? Give me a shout below…….

In the next post I will highlight the important code in the sample, and explain what it means.

*For an Ionic 3 version of the code see this post.

WordPress REST API – Mobile Apps

Standard

WordPress, not just for bloggers

I love WordPress!

Unfortunately, in my everyday job as a software engineer, I don’t get to use it much.

However, with the availability of the WordPress REST API, there are more and more reasons to use it on “real” software projects.

The WordPress REST API, in very simple terms, is a way for apps and other websites to communicate with the powerful WordPress “engine”.

Pic’N’Mix WordPress

With the WordPress REST API you can use WordPress as an ‘Application Framework’. With an application framework you can ditch the heavy blog website concept and just use the great bits of WordPress that you need in your shiny, light-weight app or website. Give your new app or website a head start by harnessing dependable WordPress engine features like user authentication, content management, media management, extensions, SEO, translations etc.

A great use case for the WordPress REST API is to use it to supercharge Mobile App development. By Pic’n’Mixing the best parts of WordPress with your mobile development technology of choice, you can rapidly get an app up and running.

Pick and mix WordPress

Pic’n’Mix WordPress

You can use WordPress as a dependable back end to your Mobile App. The mobile app stays light-weight, the only thing it needs to utilize WordPress is a Http client. If your app can make a web call, you’re all set.

But it’s not used in production apps, right?

There are some fantastic examples of apps, out in the wild, which use WordPress as a powerful back end. 3Advance were quick to recognize its utility and have created two apps already which use WordPress in the background:

Launch Alert: Meg Bitton Live iOS App gets 148 ⭐️⭐️⭐️⭐️⭐️ reviews in just 12 hours!

Launch Alert: Apps Developed to Watch and Stream Portrait Masters

3Advance are notorious for quickly turning app ideas into reality. They found the WordPress community and REST API perfect for rapid application development.

Getting Started

To get started using WordPress as your next application framework is as simple as installing a normal self-hosted WordPress site or create a site on WordPress.com.

The REST API is enabled by default on self-hosted and WordPress.com sites.

Check it out for yourself; go to your favorite WordPress site and add “/wp-json/wp/v2/posts” to the web address to see a REST API call in action e.g.

http://www.angrybirds.com/wp-json/wp/v2/posts

There are numerous examples on the internet of how you can start integrating the data returned from the REST API with your app. So instead of rehashing yet another example, here are some links below.

WordPress REST API Documentation: https://developer.wordpress.org/rest-api/

Used with a progressive web app: /wordpress-rest-api-part-2/

Used with React:

https://snipcart.com/blog/reactjs-wordpress-rest-api-example

Used with Vue.js

https://github.com/bstavroulakis/vue-wordpress-pwa

Hybrid Apps – Productivity Nirvana

Standard

So much code, written so many times

Android, IOs, Windows Phone, Web, Responsive Web; customers don’t really understand, they want their app in ALL the places. “Surely it’s the same functionality, just make it work on a different device, how hard can it be?!?”.

Unfortunately, plenty hard.

Different programming languages, different screen sizes, different App stores and different hardware makes multi platform development a pain for mobile developers. What we end up doing is re-writing the same functionality in different bespoke apps, using different languages, for each of the hardware devices; not ideal, but sometimes unavoidable. Writing the same code, multiple times is something that many of us unfortunately have to swallow.

Server Side API

There are some things we do to try to minimize the amount of code we need to duplicate on each device.

One of the approaches, to reduce code duplication, is to create a comprehensive set of web services. Using services, we can implement most of the data retrieval/manipulation and business logic, server-side. All the devices will now be able to access and use these services; code once, use everywhere.

However, these services only get us partially on the way to eliminating code duplication.

Hybrid Apps

One increasingly popular solution, to making apps that can be written once and run anywhere, is by using ‘hybrid’ development i.e. write the app in a non-native language that can be ran on ‘all’ devices. There are a slew of hybrid approaches available for developers to use e.g. ReactNative, Telerik, ManifoldJS and Ionic.

Pecheersrsonally, I have not used all of them. They all look promising, and they all have their pros and cons. However, recently, I started using Ionic (as it suited my situation perfectly) and am wholly impressed by what Hybrid development offers.

Ionic To The Rescue

My situation entailed a large SPA website, written mostly in Angular, requiring a mobile app to be created that mirrored some functionality of the website.

The thought of having to duplicate the website features, using multiple languages, and then having to support all these codebases, was horrific. We had moved as much logic to the server side as possible, but there was still a great deal of functionality in the website that could not be moved and needed to form part of the mobile app; cue Ionic.

ionic

Iconic is a hybrid mobile platform which basically embeds a website inside a mobile app. The website in the mobile app can be a normal responsive html/css/js website but can also utilize various native functionality (e.g. camera, GPS, senors etc) by calling a layer, that sits on top of the native system, called Cordova.

Since Ionic allows you to create functionality in Javascript, and we had lots of Javascript (Angular) to utlilize, Ionic was a perfect fit for us.

Rapid Application Development

Never before I have been so productive developing mobile apps. The productivity gains from using Ionic have been immense:

  • We have been able to share Angular components and services with our web AND mobile apps.
  • If we find a component or service that cannot be easily shared, it forces us to refactor and break down the item into more reusable parts.
  • Quite a bit of CSS can be re-used too (if refactored well enough) to make styling consistent, across not only mobile devices, but web too.
  • We are maintaining and testing a ‘largely’ single code base using a pervasive coding language (Javascript). A problem found on one of the form factors is fixed once and deployed everywhere.
  • One of the biggest productivity gains is with the workflow. Most of the development/debugging can be performed through a web browser. Using Ionic you are able to change your Html/Js/Css and automatically see live changes. No need to start an emulator or wait on the IO between desktop and device. Sometimes, you absolutely need to test something on a specific device, but I find, that for most work, the ‘webview’ suffices.

amost_there

Not Quite There Yet

There are some trade offs with using hybrid development in preference to native development, not least performance. But for most ‘line of business’ applications the performance is ‘good enough’.

Ionic itself is great and getting better, but has some limitations. Cordova has its limits and ‘idiosyncrasies’ and can be a pain to work with. However, just having to maintain one single codebase between the mobile platforms (with web thrown in for good measure), coupled with an awesome workflow, on apps which are ‘good enough’ for most business needs, and gets an app in clients hands sooner, makes Cordova’s ‘idiosyncrasies’ bearable.

 

Alternative Viewpoints?

This form of hybrid development has worked well for me but there are so many other workflows and frameworks out there. Has anyone any experience with the other frameworks?

Premature Optimization – My Embarrassing Problem

Standard

I have a confession, I prematurely optimize.

Looking for efficiencies in some code you have just splurged seems like too much fun. We have all done it; one moment we are motoring along, knocking features out left right and center, next minute you disappear down the rabbit hole looking for optimizations.

It feels productive though.

What if my app needs to handle 1m users? What will 0.2ms extra download time do to my SEO rankings? Will users go somewhere else if my code is not running as fast as it could?

These are all semi-legitimate concerns, but at what stage does it become essential to address them?

YAGNI (You Aren’t Gonna Need It)

The truth is, most of the times, there are plenty of more fundamental issues to address, most of them related to the question “What do users really care about?”. Optimization is only important after users decide your product is actually worth using, not before.

YAGNI - premature optimization

If anyone asks, in principle, I am totally for the essence of YAGNI (You’re Not Gonna Need It), in practice, however, my track record is mixed. Theory says we should develop minimum viable products, get these products to customers without delay, defer commitment as late as possible for irreversible decisions, reduce waste, reduce inefficiencies etc etc. But far too many times I have spent hours optimizing something which:

  • Delays the time it takes to get to the customer, thus reducing time for feedback.
  • Makes technology selections too early based on optimization concerns.
  • Creates deep and incomprehensible inheritance models, because that’s what a book told me to do.
  • Introduces unnecessary complexity to the solution which developers behind me have to take even more time to learn (decipher).

All on things that:

  1. Weren’t eventually even used in production.
  2. Didn’t need as optimized as much as they were. Not now. Not ever.

This is time I could have used discovering what users actually liked or disliked.

Permission Granted

Hopefully by confessing my problem to you that it is the first step in my rehabilitation. Next time you see me pre-optimizing you have my permission to slap me, Batman style, and shout “YAGNI”.

Deploy a Developer

Standard

Most software projects inevitably suffer, especially in the humanitarian domain, unless the huge gap between developers and end users is recognized and addressed.

One of the best ways to do this (reduce the gap between these two diametrically opposed groups) could be by actually embedding a developer in your core team on your next mission or assignment.

Why Do Projects Fail?

Over a 15 year career as a software developer I can attest to the fact that poor requirements definition is the chief culprit for failing projects. I have developed mobile, desktop and server applications, worked for several companies ranging from large corporate companies to small start up companies, in a number of diverse sectors, and the single most challenging problem with creating great software is a reoccurring one; requirements definition. End users and developers can’t, won’t and don’t communicate effectively and efficiently leading to the poor definition and implementation of requirements.

poor_requirements_definition

As you can see from the above diagram, the main reason projects fail, by a large large margin, is poor requirements definition; finding our what users need and translating this into solutions.

What’s the Big Problem?

In my experience this big problem could largely be solved by bridging the gap between the two groups at either end of the process: those who make the software and those who the software is bring made for.

But it should be easy right? We are all humans, end users are human, software developers are human (mostly).

How could there be much of a problem of communicating ideas from one group to another?

Well, it turns out, there are two big issues: developer apathy and the requirements gathering process itself.

Issue #1 : Lack of Empathy

The first issue is that transposing the ideas from a non-technical user to a technical/techhie developer (who is more comfortable talking to code than people) is a big challenge. A challenge that the software industry has still failed to adequately address and affects software projects again and again and again.

The problem is that there is a huge gulf in experience, skill sets, even the language used for the same things, between a non-technical ‘ordinary’ user and the people who sit behind desks and write code. Software developers lack the empathy to adequately understand the domain and the users.

Ordinary end users talk a completely different domain language and can have completely different experiences than desk-ridden developers.

end_user

End users, come in many shapes and sizes. They can range from the very technical to the not quite so technical.

developer

On the other hand, Software Developers are generally desk ridden, highly technical and actually take pleasure from being able to talk a different language from mere mortals.

How many times have you talked your IT department and felt like they were taking pleasure in talking down to you using highly technical terms?

I will let you into a secret, we absolutely do that on purpose!

Do not underestimate the apathy (and even contempt) that developers have for end users. We view users as inferior beings. Even when users tell us directly that they have problems using something we have built, our first instinct is to scoff and assume it is user error and they should be smarter to use it correctly.

This is genuinely what we think you are doing when you ring us with a problem.

This is genuinely the kind of thing we think end users are doing when they ring us with a problem.

Issue #2 : Noise & Barriers

So with issue #1 the problem is that the two groups have often completely different perspectives and find it difficult communicating with one another. Issue #2 is that, in most software projects, there are numerous barriers placed between the developers and end users by the actual requirements gathering process.

The two groups don’t actually get even the chance to miscommunicate directly. There are layers upon layers to make ensure that, even if a clear message is stated by end users on their requirements, by the time this reaches the developer, it has been changed into something different (a bit like a game of Chinese whispers that a lot of us played in the playground as kids).

requirements_gathering_process

The Requirements Gathering Process

Take the above simplified example of a requirements gathering process. We just want to get information from end user to developer in a clear efficient way.

At the start we have the user telling a requirements gatherer of their issues.

The gatherer generally translates these findings using their own domain knowledge into a series of documents.

These documents are reviewed by a ‘middle manager’ who filters and translates the raw requirements, again using his/her own judgement.

The middle manager produces a set of faceless requirement documents which are passed to the developer to develop.

At each step some ‘understanding’ of what the end user wanted to express is lost or mistranslated by people and paperwork.

Then, when refinements are needed, the process starts all over again.

The problem?, too many steps and too many intermediaries.

Lets get these two groups talking to, and understanding each other, a bit more. Wouldn’t it be far more effective and efficient if these two groups were allowed to communicate directly with one another?

Of course it would, but because of Issue #1: the fact that they don’t even know how to talk to one another, it is also pretty impractical.

So how do we make it practical?

Turning Apathy Into Empathy

I am not saying it is easy to achieve.

Developers don’t necessarily want to come face to face with users.

Users may feel frustrated with the prospect of having to communicate with (sometimes) abrupt and condescending developers, but, from experience, the most productive and effective projects that I have worked on have involved the end user communicating directly with the developers from day 1.

Not only is it more productive for the two groups to communicate directly but it also increases the chances that the solution produced will be usable (i.e usable by the end user), useful (actually solves a stated problem) and used (not thrown in the bin like so many other projects by users. Users will have actively participated in the creation of the solution, and have a stake in the solution created.

So here my tips, based on experience, of how to help bridge the gap between developer and end user.

  • Get developers out of the office (Genchi genbutsu). Get developers out of their comfort zone. Consider deploying them on your next mission to get them to start to understand the domain and gain empathy with users. We need developers to attempt to understand users better, having empathy with end users not only increases the understanding of the domain but also gives developers incentive to make better choices during the development stage. Giving a human face to a requirement, as opposed to a faceless requirements document is hugely influential on the decisions that developers make. This type of understanding and empathy should not be understated in affecting the quality of solution your developers produce!

 

  • Use Visuals. Using visuals, rather than language and documents to share ideas cuts out a lot of the potential miscommunication issues and helps to speed up the software development process. Best to use visuals and prototypes, both developers and uses both speak this language!

prototype

  • Develop a common domain language. Right from the beginning set out a Common language for communication, try to find a common denominator to terms and phases used by both sides.

 

  • Regular Feedback & Pilot Exercises. Fail Fast. Fail Often. Facilitate a consistent, regular, and always open, channel of communicating. Frequency is key here. For example have a weekly show & tell from developers on progress and the direction they are currently taking, allow feedback from end users that will be allowed to have an impact of the future direction of the solution. Build it, scientifically measure the feedback, and learn from the lessons end users are teaching you.

 

  • Customer Champion. It may be impractical to keep going back to all the end users regularly, but at least make sure that you have a representative user who can be called upon regularly to give feedback on choices and solution direction.

 

  • Hire a Software Developer with domain experience. Find a ready-made developer who already understands the domain. If you are lucky enough to find a developer with domain experience, hire them, your project will thank you for it.

 

  • Consider an Innovation Hub. Bring the development team permanently closer to your organisation by housing them beside your team. See Andrej Verity’s recent blog post for some great advice on how to do this in a humanitarian context.

A Challenge to You

So the challenge I put to you is, “will you consider deploying a developer with your team on your next assignment?”

Are you willing to stand up to your own IT department or IT contractors and demand a more closer working relationship?

Are you willing to drag developers kicking and screaming away from their desks and into the field? Believe me, as a developer myself, you will face resistance with this!

That is the challenge to you, it would not be a challenge if it wasn’t challenging, if it wasn’t difficult!

Clean Code Tools

Standard

Writing code is an inexact science, imperfections in your code are inevitable and add up.

Having a tool that constantly nags you to strive for perfect code is a must have for flawed [see human] developers.

 

Compiled Code

Where code analysis tools really excel is with compiled code.

With compiled code, the clean code tools not only analyse the quality of your code but also automatically fix and style it!. With compiled code you get piece of mind when these ‘automatic’ changes are made because the compiler is there to reassure you.

Thank God for Resharper!

I use these type of productivity tools religiously; in particular, for any C# or JS code that I write, I always use/need Resharper from JetBrains.

resharper_stylecop clean code

Some people might say that it is ‘lazy’, letting a productivity tool ‘automagically’ do what you should be doing out of hard learned habit. I agree, it is lazy, and I am often sloppy with my code knowing that my ‘magic helper’ will clean up after me. But, I have found that, after a while, I start incorporating the suggestions and changes that the tools give me into my ‘unclean’ code, so that the tools have less work to do and my code becomes cleaner ‘naturally’.

 

resharper uninstall clean code

Too much of a good thing?

However, you can go too far with these tools.

Not only do you start to rely heavily on these types of tool to do a lot of the basic coding for you but also some of the suggestions it make for code changes can lead to your code becoming less ‘human readable’. It is soooo tempting to accept the suggestions to lambdify or linq entire sections of your code just because Reharper tell you to do it and it compresses your code to a single line. I thoroughly recommend watching the clean code Pluralsight course or reading Robert Martin’s (uncle Bob) book on clean code, to understand why human readable code is so important.

resharper - clean code

 

Interpreted Code

Things get more trickier with interpreted code e.g. Javascript. With interpreted code you do not have the compiler to reassure you that any ‘automagic’ changes are ‘safe’. For this reason, most clean code tools for interpreted code will give advice, rather than make changes for you. However, the ‘linting’ tools for interpreted code (JS in particular) have come a long way and are an essential part of any coder’s utility belt. For instance, when writing Javascript code I now rely [heavily] on Douglas Crockford’s JSLint to tell me that have been a naughty boy (I would highly recommend all Javascript developers to read Douglas’s book: Javascript The good parts and watch his talk on pluralsight) about Javascript.

jslint - clean code

What lint/analysis/style/refactoring tools do you use everyday and cannot live without? Leave a comment below:

 

Angular – My New Golden Hammer

Standard

Web Development feels ‘hacky’

For most of my career I have been a desktop developer but a few years ago I started making the move towards web development.

The move, at first, was horribly painful. For most of my working life I was working with the safety of compilers, full featured code libraries, mature test frameworks, UI frameworks and data-binding only to be thrown into the then (and even now) ‘wild west’ of web development.

My biggest gripe with web development was “how can it be so hard to do such simple things?”. I was finding that putting a button and some input controls on a screen that saved to a database required me to write waaaayyyy too much code. Never mind all the problems with screen size and browser compatibility, even simple things felt verbose and ‘hacky’

. silverlight_logo_large_verge_medium_landscape-300x169

Silverlight – Desktop like, but flawed

I quickly retreated back from pure Javascript/HTML/CSS development to using something more ‘desktop-like’ and started using, and advocating, Silverlight.

Silverlight is [was] Microsoft’s attempt to replace Flash (more or less). Things were good, I was productive again and spitting out highly functional web apps until I started fully realizing the limitations of using a plugin based approach. On the brink of giving up web development due to frustration, I started looking at the latest web technologies that were beginning to gain some traction.

Knockout JS. Better, but still too many dragons to slay…

knockout

The first bit of relief came when I discovered Knockout.js. Knockout is a fantastic library that enables easy MVVM data-binding in your web apps. This was more like it, not having to write as much ‘grunt’ code to hook up data with UI felt much better. Something as simple as the data-binding that knockout gave me renewed my enthusiasm for web development and I started to look for other libraries that could address the other reservations that I had about web development.

AngularJS-large

Angular, now we’re talking

The next discovery, and most fruitful, was AngularJS.

Angular is a Javascript library from Google which makes web development sooooo much easier. For almost every problem that I started to ask Angular it seemed that the developers had already had the same pain and had already built the functionality into Angular already. If there was something that I needed from the framework that didn’t already exist, there was usually an Angular extension that was readily available or I was able to make a directive from an existing Jquery plugin.

Angular has become so much of a golden hammer for me that I find it hard to contemplate starting a large website without using it.

Looking to the future

The landscape for web development is evolving rapidly but with frameworks like Angular, and maturing and adherence to web standards, it does not seem as anarchic as it once was. There are several other libraries that have made my life easier such as underscore/lodash, twitter bootstrap, and breezejs, but the underlying library that has made the most difference is Angular. Since converting to Angular I am now a happy and more productive web developer. Before, I was extremely frustrated and unproductive and although Angular, and web development in general, is still far from perfect, it is a more enjoyable place to be.

A Word of Caution for Angular 2

Before you get carried away and start seeing everything in angular tinted glasses, you need to consider the ramifications of the upcoming Angular 2.0.

I have had a look at the 2.0 syntax and it is a big departure from 1.x. IMHO this is a strange and worrying decision from Google as many people looking to dive into Angular at this point in time will be uneasy that the code they write now will not be supported/current in the near future.

2 Golden Hammers?

Although promises of a clear upgrade path are promised by Google, it might be time to find a backup golden hammer (i.e. React) to hedge my bets.

Has anyone else got similar experiences with Angular? Have you found other libraries that you feel you cannot do without? How do you see the future for frameworks like Angular, React, Backbone or Ember?

Why Write This Blog?

Standard

I write code for a living, I love doing it, but I want to do it better.

I forget things, really important things.

Birthdays, meetings, anniversaries, names, outstanding bills, all fall victim to my absent-mindedness; nothing is safe. As programmers we have better things to do with our time, right? Why should we have to remember trivial things like anniversaries when there is code in front of us to crank.

Most of us coders don’t have a personal assistant to keep us on track, and most of us don’t conform to the basement-dwelling, cola drinking, RPG playing, colostomy bag wearing, nerdy stereotype (at least not all of the stereotypes). We are ordinary folk who just like as little distraction as possible while engrossed in some code.

programmers

So what to do, how can we still keep our heads in code while having as few untimely interruptions from the outside world as possible?

Over the past few years I have been gradually getting better at remembering and organizing things. By using widely available software programs and apps I have able to save face on several occasions now, but things are still not perfect.

This blog chronicles my attempts at learning, from current tools and practices, and from you, about what I am doing wrong and how we can do it better.

Left to my own devices I can be a lazy and unproductive programmer.

I am scatterbrained; forgetting meetings, birthdays and names.

I fret that I will forget important things and so try to deal with them as soon as I encounter them or just sweep them under the carpet.

Procrastination is a habit that I cling onto like a life raft when things start to get difficult.

I like to think of myself as a typical coder 🙂

productivity

BUT,

One redeeming quality that I do have is that I know that I have these flaws and recognize that they stop me from being a better programmer.

Procrastination makes easy things hard, hard things harder.

Mason Cooley

 

I have been around just long enough to know that there is hope for coders like me. I know there exist tools, practices and tips that will enable me to shake the shackles of these common programmer traits and become a more rounded, confident and productive coder. This blog is about exploring these topics and getting opinions on what works and what doesn’t.
EDIT:

LOL! in the course of writing this post I found myself spending an hour [2 hours]: looking for an avatar, browsing Facebook and looking at a whole host of memes from quickmeme.com.