RESTful Web API Design

An API is a set of routines or functions. It’s an interface used for performing tasks, retrieving data, and manipulating data. APIs use HTTP methods, which are used on a resource to GET, POST (submit form data), PUT (for updating files), PATCH (a partial update), and DELETE.

Adding an API

  • Bolt-on strategy – when you already have an application and are adding an API to it
  • Greenfield strategy – no underlining application. There’s complete freedom and flexibility to do what you want. Generally the “API first” or “mobile first” mentality.
  • Facade strategy – wraps existing logic with replace as you go. This is ideal for legacy systems so the application is always functional.

Designing the Relationship

  • Independent – the resources may exist regardless of the other existing but they may reference each other
  • Dependent – one resource cannot exist without the parent
  • Associative – they are independent of each other but the relationship contains additional properties to describe it

Planning the Relationships

  • Ask yourself the following questions:
    • Can both resources exist without the other?
    • Does one resource only exist when the other exists?
    • Does the relationship between resources require more information than just the links between them?
  • It should be relatively easy to map out the flow, action, etc for each resource. If not, you need to revise your design.
  • Consider using notecards to write down each resource action

REST

  • REST stands for Representational State Transfer
  • It’s an architecture for designing network-based applications
  • It is not a protocol, framework, or standard

Benefits of Stateless Servers

  • Visibility – monitoring systems and developers do not need to look beyond the request to trace a bug
  • Reliability – easy to recover from system failures

Drawbacks of Stateless Servers

  • Network Bandwidth – client sends state for every request
  • Complexity – all clients must handle their states

Benefits of Caching

  • Performance – for stateless and caching, many requests do not need to go all the way to the server
  • Scalability – server gets fewer requests so it can handle more clients

Drawbacks of Caching

  • Data reliability – clients might use stale data

Facets of a Uniform Interface

  • Self descriptive messages
  • Server includes metadata, such as Content-Type, to help clients process the responses
  • Hypermedia as the engine of application state (HATEOAS)
  • Client only assumes a fixed entry-point to the API, the server tells clients all other available actions through hyperlinksBenefits of a Layered System
  • Encapsulation (simplify an interface to a legacy server)
  • Scalability (layers enable load balancing)
  • Security (add access control rules to data crossing a boundary, just like a firewall)

Drawbacks of a Layered System

  • Latency – adding layers increases latency

A Brief Overview of GraphQL

GraphQL is a query language designed to make data fetching easier. It allows you to get data from the server to the client. It is language agnostic and became open source in 2015.

Overview

  • Input types include: integer, float, string, boolean, null, enum, list, object
  • It has a built-in documentation for the schema
  • Can create operation names to help identify different queries
  • Creates changes through mutations
  • API determines what mutations are allowed

Benefits

  • Avoids multiple REST calls
  • Is backward compatible and version-free
  • Can wrap around existing APIs
  • Queries can have comments

 

A Brief Overview of AWS

Amazon Web Services provides on-demand cloud computing platforms for individuals and companies. Here is a basic overview of some of the possible services and terms involved with AWS:

Elastic IPs

  • Work well for emergencies
  • Instead of a different IP for each different server, there’s an IP for the account that can be rerouted for servers

Elastic Load Balancing

  • Component for balancing network traffic
  • Scales request handling to meet traffic demands
  • Supports HTTP, HTTPS, and TCP traffic
  • Supports health checks
  • Automatically scales based on demands placed on it
  • Single CNAME for DNS configuration

CloudWatch

  • Allows to monitor resources automatically
  • Watches resources, SPU, Disk i/o
  • Network traffic, alarms, custom metrics

Optional Detailed Monitoring

  • Higher frequency intervals of data capturing
  • More pre-defined metrics
  • Monitor aggregate metrics across similar resources

Elastic Block Storage

  • Volumes up to 1TB
  • Attach multiple volumes to a single instance
  • Specify I/O performance
  • Format with a file system, use like any other block device
  • EBS snapshots
  • Lazy loading of data to new volumes

Relational Database Service

  • Specify performance size
  • Can monitor the health with CloudWatch
  • Updates applied for you
  • Automatic backups
  • High availability/scalability/fault tolerance

Bootstrapping

  • The process to get an application up and running on an EC2 instance, or other AWS services
  • Bootstrapping tools – running custom scripts to configure settings, start services, apply updates
  • AWS give access to the instance metadata
  • Bootstrapping tools: Cloud-Init (Linux), EC2Config (Windows)

Getting Started with PHP

The other day I worked on putting together a PHP CMS from scratch, and I learned a little bit about how to set up my environment for running the application locally. So for anyone who is looking for a bit of a reference, below is more information outlining the steps for setting up the environment.

Mac Installation

  • The web server (Apache) involved with PHP applications is built-in with a Mac
  • httpd -v (on command line to see what version of apache is installed on machine)
  • ps aux | grep httpd (to find out if apache is running on machine)
  • Apache commands:
    • sudo apachectl start
    • sudo apachectl stop
    • sudo apachectl restart
  • Create Sites folder within same area as Desktop folder
  • navigate cd /etc/apache2/users
  • sudo atom username.conf
  • sudo chmod 644 username.conf
  • sudo apachectl restart

Enable PHP

  • php -v (returns version of php)
  • cd /etc/apache2
  • sudo atom httpd.conf (opens config file, search for php, remove # before LoadModule for php to enable php5)
  • phpinfo() helpful method that tells you all the configurations for the version of php you’re using
  • Database (MySQL 5.x)
  • download from https://dev.mysql.com/downloads/
  • which mysql (command to find location of mysql)

Additional Info

  • echo is used to print text
  • For comments, // and # are used for single line

How PHP Communicates with the Browser

The browser sends a request to server (Apache). Apache finds the file, processes it if it requires processing (sometimes it might need to go back and forth between the database), then it assembles the html and ships it back to the browser.

A Brief Overview of Angular JS 1

Angular JS is a front-end framework for web applications. It allows you to extend HTML’s syntax to present dynamic content through two-way data-binding.

  • Angular directives are special commands used within the framework
  • All directives start with ‘ng-‘ then the name of the directive
  • Expressions are written in the HTML and are wrapped with {{ }} which is used to add JavaScript within the HTML
  • Two-way data binding ties the view and model together
  • Angular is used for the view in MVC architecture
    • M is for model (or data)
    • V is for view
    • C is for controller (JavaScript that links your data to your template, creates the interaction between your model and your views)
  • Modules are specific JavaScript files used to take care of different tasks
  • Service is a small piece of code that takes care of common tasks
  • $http is a service that handles communications between an http server and your application
  • Deep linking looks at the location URL and manages how it maps to the current state of the page
  • $scope service allows you to pass variables between the JS and the HTML

Directives for form validations:

  • ng-required
  • ng-minlength
  • ng-maxlength
  • ng-pattern

Properties for the models:

  • $pristine (class ng-pristine)
  • $dirty (class ng-dirty)
  • $touched (class ng-touched)
  • $valid (class ng-valid)
  • $invalid (class ng-invalid)

A Brief Overview of JSON

JSON stands for JavaScript Object Notation. It’s the text format used for sharing data, and is the most popular data transmission format. JSON is used for local data while JSONP is used for remote data.

Here are a few other things to keep in mind about this data format:

  • JSON is language independent (it’s available in php, Python, etc)
  • JSON keys are wrapped in quotes
  • JSON keys can be any valid string
  • Special characters can make it difficult to access data, and you should use underscores instead of hyphens
  • JSON has to be parsed into JavaScript (which can be done with eval or JSON.parse – JSON.stringify does the opposite of parse)
  • A great alternative to XML

JSONP

  • Stands for JSON with padding
  • Used for cross domain requests
  • Request URL incorporates the name of a callback function according to syntax defined by the service you’re using

Response Formats

  • JSON object
  • JSON array
  • JSONP (function)
  • Browsers enforce same-origin policy

Cross-Site Script Injection (XSSI)

  • Protecting against XSSI – can strip out malformed code
  • If downloaded directly, it isn’t parsed and creates an error

Alternatives to JSON

XML

  • Extensible Markup Language
  • Was widely used before JSON became popular
  • We can convert JSON to XML with different services

YAML

  • Was created to be human readable
  • Another language used to interchange data on the web
  • Uses white space, including indents and blank lines, which increases the size of YAML but makes it easier for humans to read
  • Uses key value pairs
  • Strings don’t need to be quoted
  • Supports explicit data typing
  • Supports single-line comments that are denoted by # (JSON doesn’t allow commenting)
  • JSON is good for basic use cases and has parsing built into JavaScript, while YAML is not directly usable in JavaScript

A Brief Overview of PHP

PHP is an open-source, server-side scripting language that was designed to be used with HTML. It can be object-oriented, and here is an overview of some of its features:

Data Types

Arrays

  • To create a variable and assign it to an empty array, use the following format $newarr = array();
  • To create a variable and assign it to an array, use: $newarr = array(1,2,3,4,5,6);

Associative Arrays

  • Associative arrays are an object-indexed collection of objects, used when you need a key to retrieve data.

Constants

  • The value of constants doesn’t change.
  • Use quotes when defining the constant, define("CONST_VALUE", 10), once it’s been defined, don’t use the quotes when referencing it.
  • You can’t redefine constants.

Booleans

  • When PHP outputs ‘true’ into a string, it outputs 1. For ‘false,’ it outputs nothing.
  • To check if a variable is a boolean, use is_bool();
  • True and False can be written in uppercase or lowercase

Floats

  • round(number1, number2) takes a number and how many significant digits you want there to be
  • ceil(number) ceiling always rounds up
  • floor(number) floor always rounds down
  • is_float(number) to determine whether something is a float

Functions

  • strtolower() changes a string to lower-case
  • strtoupper() changes a string to upper-case
  • ucfirst() changes first letter in string to upper-case
  • ucwords() changes first letter of every word in the string to upper-case
  • strleng() finds length of the string
  • trim() eliminates white spaces
  • strstr() find a string within a string (pass two parameters). Find a string within a string
  • str_replace() takes three parameters – the string you’re looking for, what you want to replace it with, and the item we’re searching in

Integers

  • abs(0 - 100) absolute value
  • pow(3, 6) exponential (first number to the power of the second number)
  • sqrt(25) square root
  • fmod(17, 3) modulo
  • rand() random
  • rand(1,20) random (min, max)
  • is_int(number) to determine whether something is an integer

Null and Empty

  • Case insensitive
  • is_null(); will test if an item is null
  • An empty string, null, 0, 0.0, “0”, false, and an empty array, are all considered items that are empty

Strings

  • Strings can include letters, text, html.
  • Use double quotes or single quotes to denote strings
  • Can do variable replacement inside of a string (but only when you use double quotes):
  <?php
  $phrase = "Hello World";
  ?>

  <?php
    echo "$phrase printed here<br>";
  ?>
  • For in place substitution, use echo "{$phrase} Here<br>";

Debugging

  • Use <?php phpinfo(); ?> to access more information about the configurations
  • Missing semicolons are a common problem
  • To turn on error reporting, in the php.ini file, display_errors = On and error_reporting = E_ALL, in PHP code, ini_set('display_errors', 'On'); and error_reporting(E_ALL);
  • Turn off error reporting on live websites
  • Use echo to make sure you’re getting the right values for variables
  • print_r($array); to print readable array
  • gettype($variable); to get variable type
  • var_dump($variable); to get type and value
  • get_defined_vars(); array of defined variables
  • debug_backtrace(); show backtrace

Encoding

  • For GET requests to pass a reserved character, you must encode them with urlencode($string) – letters, numbers, underscores, and dashes will be unchanged, but reserved characters become % + 2-digit hexidecimal, and spaces become +
  • For rawurlencode, letters, numbers, and dashes are unchanged, reserved characters become % + 2-digit hexidecimal, and spaces become %20
  • Use rawurlencode for the path, before the “?” section, and uses urlencode on the query string
  • <, >, &, and ” are reserved characters in HTML
  • HTML can be encoded with htmlspecialchars() and htmlentities()

Printing

To print items to the screen, use echo

Variables

  • Start with a $ followed by a letter or underscore
  • Can contain letters, numbers, underscores, or dashes and can’t contain spaces
  • Case-sensitive

How to Add a Script to Minify your JavaScript in a package.json file

Recently I was working on a project where I wanted to set up a process that could combine and minify the JavaScript I had in a specific folder for a project. So how did I do it?

I decided to run the npm init command on my project folder. Within the package.json file, I had the following:

{
  "main": "scripts.js",
  "scripts": {
  "minify": "uglifyjs ./js/* -o scripts.min.js",
  "uglify": "npm run minify"
},
  "dependencies": {
  "uglify-js": "^2.8.8"
},
  "devDependencies": {
  "uglify-js": "^2.8.8"
 }
}

Once I ran npm install uglify-js --save, I made sure to specify the folder I wanted to run the process in (./js/*), and the file I wanted to create with the minified code (scripts.min.js). Next, all I had to do was run npm run uglify and my new scripts.min.js minified file was created.

Now whenever I make changes or add new files to my project’s JavaScript folder, I can run npm run uglify to bundle up and minify the code.

A Brief Overview of ES6

ECMAScript 6, or ES6, is a newer version of JavaScript. It has several unique capabilities that weren’t possible in previous versions of JavaScript, for example:

  • Variables can be set with the terms let and const
  • The let keyword is used for block scoping so it doesn’t affect global values
  • The const keyword is used to protect the value of certain variables – you use this keyword for values that shouldn’t be reassigned
  • It allows you to use template strings to tap into the functionality of template languages to format your JavaScript code with variables like so: `${yourVariableHere}`
  • The spread operator can turn elements of an array into arguments of a function call or into elements of an array literal
  • Allows us to make classes in JavaScript (can create one super class that other classes inherit)
  • Can pass default values in functions for when you don’t explicitly pass anything for them

In order for browsers to understand ES6, you need to transpile the code. Babel, Traceur, and Closure are used for transpiling code, although Babel is known for supporting the most ES6 features.

For larger scale projects, you can use build tools like Webpack with ES6 – this allows us to load our dependencies. Npm creates a package.json file that runs dependencies.

 

Yarn: the JavaScript Package Manager

If you already use npm, you’re probably wondering what’s the point of Yarn?

Yarn is a somewhat new JavaScript package manager created by the engineers at Facebook.

  • It’s a faster and more secure dependency manager
  • It uses an offline cache – so after you’ve installed a package using Yarn, it will be available on your machine for offline access.

Quite honestly, what really reeled me in with Yarn was the speed at which it can install packages. It’s amazing how shaving off a few seconds from installing packages can really speed up your overall workflow.

Get Yarn

npm install –g yarn

Or use brew to add it. Once installed, you use the following format to add any dependency:

yarn add <name of package>