the power of a great api

31
The Power of a Great API the case for writing API-first applications Damian Brady Octopus Deploy @damovisa | @octopusdeploy

Upload: damovisa

Post on 14-Apr-2017

266 views

Category:

Software


0 download

TRANSCRIPT

PowerPoint Presentation

PrepStart ZoomItOpen Postman with localhost:12345/api/questions already thereGit reset to masterCheck snippetsClose everything on Mac

The Power of a Great APIthe case for writing API-first applicationsDamian BradyOctopus Deploy@damovisa | @octopusdeploy

2

Who am I?Solution Architect at Octopus DeployI run DDD BrisbaneMicrosoft ALM MVPCo-author of a Professional TFS 2013 book

Background in web dev, consulting, mentoring

AgendaWhy is an API a good thing?ImplementationDemo

I need one button to disable all the machines in an environment

At Octopus Deploy, everyone does support. Vanessa is our support guru, but every day, one or two developers handle support emails and tickets with her.I was still very new when I got this ticket.This is quite specific to our application, but in Octopus, you define Environments, and each Environment has a machine. This customer wanted to disable all of the machines in a particular environment.

If youre familiar with Octopus Deploy, you might know how you disable a machine.Its fairly basic, in our UI, you find the machine, click on it, then check the Disable checkbox and Save.Simple, right? Just do that for each of the machines.

But what if this is what your environment looks like?We havent made it easy to disable all of them.6

So whats the solution?Sorry, youre going to have to do it 200 times

So whats the solution?Well add this feature on the next release!

Sometimes theyre good ideas. If you can prove it first8

So whats the solution?Heres a script

But its also handy for extensibility9

We need an iPhone app!

Usually you dont but hey, I dont know youre business.Either way, this doesnt have to be your reaction10

Application Programming Interface

By writing your app API first, youre not binding yourself to a UI.Youre enabling a way for any software to use your application any UI, or any non-user interface.

The same as a UI gives access to a user, an API means access to software. If done correctly, that means any software.So when your manager comes asking for an iPhone app or an Office integration or for a particular report to be run when the temperature goes below 5 degrees,it doesnt turn into a collective groan followed by long discussions about how its too hard. It becomes a largely trivial request.

And in the case of the iPhone app, you can probably outsource it. In fact, maybe someones already done it for you Theres a GitHub iPhone app called ioctocat.The app on the right is called AlienBlue, and it was an unofficial Reddit app which used their API until Reddit bought it.

That happened because the API existed11

Walled gardens are soooo 2000

Closed platform, Closed ecosystem, walled garden12

Extensibility

Twitter used to be on the absolute forefront of being an open ecosystem. In August 2012, they capped the number of users a third-party app can have to 100,000 and received massive backlash.

The argument was they wanted to push more people through their website for ad revenue and consistency across devices. However this meant crippling the Twitter ecosystem. Those hundreds and thousands of apps that fed from and to Twitter.

Of course it hurt developers creating apps MetroTwit (for example) effectively, despite being an extremely popular Twitter client, didnt think it was worth continuing.But it also hurt Twitter admittedly not a great deal (theyre rolling in cash), but by keeping tight control on how Twitter was used, they risked losing a lot of users.

You might not be writing the next version of Twitter but Id argue thats even more reason to expose an APINow, whether this was ultimately a bad thing or not, it made a lot of people angry. Twitter removed a feature they were known and loved for, and it upset people.

13

Extensibility

UNTAPPD

Have you heard of UnTappd? Its a social app where you check in the beers you drink it lets you rate them, tells your friends about it, etc.It uses the FourSquare API to get location data the names of pubs, clubs, restaurants, etc.It also uses the Twitter and Facebook APIs to post this information to your friends.

But recently I discovered another app/website called Now Tapped. With the rise in craft beers, a lot of pubs change what they have on tap on a regular basis. Now Tapped is a tool that tells you whats on tap at different venues. Now, not every venue gives this information directly to Now Tapped so for those venues, the information is available on UnTappd if someone checked in a particular beer at that pub 20min ago, theres a good chance its on tap!14

Extensibility

API != Public API

Look, maybe your application doesnt make sense as a public API. But it doesnt have to be. You can get huge benefits simply by writing it that way support and future-proofing.A lot of the time, the reaction against a public API and even from an API in general comes from the top.

Why build in this complexity if were not going to use it especially because weve worked hard on this, why would we give it away?16

Why would I do that?You cant predict the future

Your app might be useful in a way you didnt predict

Someone can use your functions better than you

Ultimately, it comes down to a few things.

You cant read minds and you cant predict the future as much as you think you know your customers and your product owners theyll surprise you. Building an architecture that lets you react fast is important.

Similarly, maybe people want to use your application in ways you dont expect. An API can give you that option.

And heres the worry that comes from the top. Maybe were not the best at the UI. Or maybe you just dont have the skills or self-loathing to write that iPhone app.17

Implementation

UIBusinessDataExceptionshttp://hdwyn.com/glacier_iceberg_under_water_hd-wallpaper-14494/

You all layer your applications right?

You have a UI layer, business layer, data layer exceptions fall into this deep pit its like an iceberg and your users can only see above the water.

Now thats sometimes often good. We all know theres plenty of stuff underwater that would give you nightmares.

So Im not saying you should pull the iceberg above land, Im just saying float it a bit higher.

Your API should be at the surface above any business logic, but below the UI.19

API FirstFocus on your function

Make your UI use your APIUIAPIDataBusiness

Shift your focus from the nice pretty UI to the functions your application performs. This is the stuff only you can do, and its the valuable part.

Its really important to make that the focus your API and the functions it exposes. Your UI should just be a consumer.

This opens the door to all those advantages we spoke about earlier.20

API Second?Expose your Business layer

Refactor or add a layer

Make your UI use your APIUIDataBusinessAPI

You already have an application? Well, expose your business functions.If theyre too specific or dont make sense outside the context of your internal app, refactor

If possible make your UI use your APIIf thats not feasible at least make your API an extremely thin layer over your business functions.21

One code path

The most important thing here is to make sure all your code follows the same code path as API calls.No additional logic, no secret functions.

If you dont make your UI go through the API, youre inviting technical debt.Try to make it impossible for your UI to get anything done any other way.Its fairly common to get lazy and bypass the API. This is working with secret knowledge, and it might seem reasonable at the time. However, its dangerous:Validation is a great example of where this can happen. If your UI and the API travel down different code paths, you might not validate an email address properly.

22

ImplementationThere are plenty of optionsbut HTTP is easy

Self-hosted endpoints OWIN, NancyFX

PM> Install-Package Microsoft.Owin.SelfHostPM> Install-Package Nancy.Owin

Types of Web APIsHTTP/RPC

Remote Procedure Call

Method calls over HTTP

Request-responseREST

REpresentational State Transfer

Resource-based URIs

HTTP Verbs

Stateless

HATEOAS

Hypermedia As The Engine Of Application State

REST + links

Self-describing

Traditionally, people in my position will tell you to strive for REST or HATEOAS.REST is a great way to work with resources. Things that get created, edited, and retrieved. But not everything sits well in that model.

If were going to be realistic though, youre probably going to have to use RPC sometimes. And thats ok.Lets say you have a function in your finance app that takes some details about a loan and gives you an interest figure.Now you could use REST (create a new loan calculation resource, and the response comes back with the result)... But youre really forcing your application into REST. Do you want to get that calculation resource back later?

HATEOAS is a fantastic goal which makes API discovery really easy for people, but that might not be what you want.

RPC: Flickr - https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=16170e68aa2b07d112c028c5eb9be18b&text=ddd&format=json (or https://www.flickr.com/services/api/explore/flickr.photos.search)REST: Spotify - https://api.spotify.com/v1/artists/1QxaPWG1POM8Ul6WwsHq4yHATEOAS: GitHub - https://api.github.com/

24

HTTP/RPChttps://api.flickr.com/services/rest/?method=flickr.photos.search&text=melbourne&api_key=xxx

RESThttps://api.spotify.com/v1/artists/1QxaPWG1POM8Ul6WwsHq4y

HATEOAShttps://api.github.com/

emojis

Be pragmatic

Heres my advice.Dont try to force your application into REST.

Dogmatism is a great way to write an API nobody uses.28

What to include?CRUD for Resources + Sensible functionsPOST, GET, PUT, DELETE/api/customers/1/api/customers/1/addresses/api/customers/1?includeDetail=true/api/customers/1?detailLevel=2

Be pragmatic

Use separate classes

Too many options is leaky.

Its better to err on the side of too little and expand only when you need to.

Its ok to have multiple calls29

Other optionsOData?

/api/Customers(1)/Orders?$filter='Total gt 10000'&$take=5&$orderby=Total,Date desc

GraphQL?

Im not a fan. Its your data and your application protect it!

The first API Microsoft released for Visual Studio Online was an OData API. It was fairly quickly abandoned because it let people put in queries that ran for several minutes.

GraphQL from Facebook is interesting the client is what specifies the structure so rather than the server deciding what the data looks like, the client can ask.Yet to be seen how youd implement it30

More things that might hurtLong-running Tasks

Security

Versioning

Caching

Content negotiation

Versioning sucks you wont find a silver bullet here, no matter who tells you they have one.As long as you think about it before you start, youre on the right track. Use your Pluralsight subscription to look for a session by Shawn Wildermuth.Think about how many concurrent versions you will support, what it looks like when you phase a version out, how to store data for multiple versions, etc.

You have the same issues for Caching as you do for Web apps. In general, if data doesnt change, or changes infrequently, caching can be useful. Keep in mind though, that if someone creates or modifies a resource, theyre going to expect to see those changes straight away.

Content negotiation is neat, but dont go out of your way if youre finding it hard. NancyFX has excellent OotB support for it (as well see), but as long as you speak JSON, thats usually enough.

31

ArchitectureThe Principle of Least Surprise

The Pit of Success

Be conservative in what you send, be liberalin what you accept

It all comes down to being predictable, both with your URLs, and the data you accept and return.

Pick a plurality. Honestly, it doesnt matter, but stick to it.Similarly, dont have different URL patterns for similar items32

ArchitectureConsistent URIs/api/customers/1/api/order/1/api/customers?top=5/api/orders/top?count=5

Consistent objects/api/customers/1

/api/customers

Consistent objects for collections, search results, and single items your Customer should look the same no matter where it comes from

33

Demo

34

RecapWhy is an API a good thing?ImplementationDemo

ThankyouDamian BradyOctopus Deploy@damovisa | @octopusdeploy