API DESIGN

IN THE WORLD OF ANGULAR

SPEAKER

{
	"name": "ng-henry-ruhs",
	"description": "Senior Frontend Engineer at Avantgarde Labs",
	"version": "1.9.82",
	"license": "GPL-3.0",
	"keywords":
	[
		"CMS Founder",
		"Frontend Architect",
		"JavaScript Evangelist",
		"WPO Expert",
		"GitHub Fanboy"
	],
	"website": "https://redaxmedia.com",	
	"twitter": "https://twitter.com/redaxmedia",
	"github": "https://github.com/redaxmedia"
}

API DESIGN

OVERVIEW

ISSUES WE FACE

HOW TO CREATE A FAKE API

AGILE DESIGN WORKFLOW

SECURE YOUR PUBLIC APIS

UNLEASH THIRD PARTY APIS

RECOMMENDED PACKAGES

CONLUSIONS WE DRAW

API DESIGN

ISSUES WE FACE

"Houston, we have a problem"

1. No abstraction layer via API

2. Query builder in the frontend

3. Business logic in the frontend

4. Mapping inside Angular services

5. Hard coded authentication header

6. Misleading HTTP methods

7. Misleading HTTP status codes

API DESIGN

HOW TO CREATE A FAKE API

"If you can't make it, fake it"

JSON SERVER


npm install json-server

json-server db.json
{
	"departments":
	[
		{
			"id": 1,
			"name": "Jewelery"
		},
		{
			"id": 2,
			"name": "Clothing"
		}
	]
}

FAKE DATA

const _ = require('lodash');
const faker = require('faker');
const departments = _.times(1000, id =>
{
	return(
	{
		id,
		name: faker.commerce.department()
	});
});

module.exports = () =>
{
	return(
	{
		departments
	});
};

json-server db.js

npm install lodash faker

"Time for a live demo"

API DESIGN

AGILE DESIGN WORKFLOW

1. Start with a fake API

2. Create the basic endpoints

3. Add the known properties

4. Add the routes and middleware

5. Implement the Angular services

6. Render the views with fake data

7. Extend the properties as needed

8. Finish the frontend and fake API

9. Develop the backend API

10. Implement the backend API

API DESIGN

SECURE YOUR PUBLIC APIS

1. Prevent hard coded credentials

const headers = new HttpHeaders().set('Authorization', 'dGVzdDp0ZXN0');

this.http.get(this.url, this.payload,
{
	headers
})
.subscribe();

2. Authorization via middleware

3. Use read-only credentials

4. Validate client with X-Header

const hash = require('hash.js');
const headers = new HttpHeaders().set('X-Token', this.createToken());

createToken() : string
{
	return sha512()
		.update(
		[
			navigator.userAgent,
			navigator.platform,
			location.href
		].join(':'))
		.digest('hex');
}

API DESIGN

UNLEASH THIRD PARTY APIS

"Let's hack some code"

API DESIGN

RECOMMENDED PACKAGES

NGX AUTH


npm install ngx-auth

NGX CRUD


npm install ngx-crud

"Looking for suggestion!"

API DESIGN

CONCLUSIONS WE DRAW

1. Build the API for your frontend

2. Ignore the existing backend

3. No mapping inside frontend

4. Find edge cases using fake data

5. Develop on a local running API

6. Never mix the environments

7. Consider using a middleware

THANK YOU


process.exit();

API DESIGN

By Henry Ruhs