API Simplicity == Speed; Designing APIs That are Easy and Fun to Use

61
API Simplicity == Speed Designing APIs That Are Easy and Fun to Use Harold Madsen, API Director @ Ancestry.com Positions: Platform Initiative + External APIs + Notification + Community Speaker: API Strategy (San Fran), RootsTech (SLC), FamilySearch DevCon (BYU) September 18, 2014

description

This hands-on presentation teaches participants how to design APIs that are simple and consistent to use. If your API is easy to use then it will be more likely to be adopted and will speed product delivery. This presentation will be given at BYU during the FamilySearch Developers Conference 2014

Transcript of API Simplicity == Speed; Designing APIs That are Easy and Fun to Use

  • 1. API Simplicity == SpeedDesigning APIs That Are Easy and Fun to UseHarold Madsen, API Director @ Ancestry.comPositions: Platform Initiative + External APIs + Notification + CommunitySpeaker: API Strategy (San Fran), RootsTech (SLC), FamilySearch DevCon (BYU)Publisher: InformationWeek.comSeptember 18, 2014

2. AgendaI. Design ConceptsII. Design PrinciplesIII. REST StandardsIV. Client Proxy StandardsV. Sum It UpFrederick Douglass, abolitionist 3. 3Design ConceptsBefore we talk API standards, lets cover some concepts 4. Design AffordanceHow A Physical ItemIs DesignedInstructsHow Its UsedPsychologist James J. Gibson originally introduced the term in his1977 article "The Theory of Affordances and explored it more fullyin his book The Ecological Approach to Visual Perception in 19794 5. Design Matterswww.baddesigns.com5 6. Design Matters for APIs Too Good, Bad and the Ugly Used a Bad API? What is it like going to work each day?6AddressVerifyCallbackDoCaptureDoVoidMassPaymentGetBalanceTransactionSearchUpdateRecurringPaymentProfileSetExpressCheckOutRefundTransactionEtc.account.GetBalance()payments.GetInvoice()payments.Void(invoiceId)payments.Search()Etc. 7. API Smell Test Does It Pass the Smell Test? Methods tSndMl MyEventType -> lets use verbs Parameters SendMail(var1, var2, var3, var4, var5, var6, var7, var8);- Maintainability, extensibility, and backwards/forwards compatibility URLs https://somedomain.com/cgi-bin/prod/load_survey_mysql?rater_id={id}7 Service Name: OREM 8. A Pragmatic Approach to Great APIs8- Brian Mulloymake for happy developersRESTful API Design@landlessnessConsistent APIsDesign for simplicityand ease of useKeep the client (developer)in mind 9. Programs must be writtenfor people to read, andonly incidentally formachines to execute9- Abelson & SussmanStructure & InterpretationOf Computer Programs 10. Design PrinciplesWhat are Ancestry.coms guiding principles?10 11. Design Guidelines Design with Developer in Mind Be Consistent help developers guess the answer Your API should be Obvious what it is and how to use it Good Designs Take Time you have permission Decide as a Group 2+ heads make better decisions11 Avoid method-driven approach 12. ConsistencyHelp Developers Anticipate Your Thinking Standard URL Patterns collection/item/collection/item Collections are Plural persons, trees, events Standard Terminology personId, recordId, collectionId, treeId, UserId PID Standard Error Responses12 13. Its All About Consistency Time To Market Developer Happiness Productivity13 14. 14Two roads diverged in a wood and II took the one less traveled by,And that has made all the difference. Robert FrostREST ClientProxies 15. REST StandardsREST Standards that bring consistency15 16. Building the Dog API(Brian Mulloy inspired)16 17. Starting Point How to Interact with a Dog API Often a Method Driven Approach When Building the App The developer creates a method then discovers He needs an API to complete his method Pretty soon you have a mess Lets take a look17 18. Dog Service (method-driven approach)18 19. Whats Wrong with our Dog API? Verbs are at the beginning and at the end Some have verbs and some dont API is not guiding the developer No consistency Also, the chances of new hires improving the code are not good infact, the chances of them making it more confusing are very good! Why? Again, lack of consistency.19 20. A Dogs World Is Big!20 21. Way Big!21 22. Dog Service (Expanded)22 23. This can become a slippery slope, soKeep the simple things simple23 24. Keep It Simple24Please, somethinggood happen! 25. 2 Base URLs Per ResourceThe first is for a collection:/dogsThe second is for an element:/dogs/123425 26. HTTP Verbs CRUDPOST CreateGET ReadPUT UpdateDELETE Delete26Use 4 HTTP Verbs 27. API Design Table27ResourcePOSTcreateGETreadPUTupdateDELETEdelete/dogsCreate anew dog {dogId}/dogs/1234 28. Lets Have Some Fun! Lets design a Dog REST API Whats yours going to look like? Lets go to the board and design it together Well take 9.571 minutes Who will our leader be? Questions before we start??? Go!28 29. 10 Minutes For API Design 30. 1 Minute PresentationsYouve Got 1 Minute To Present!30 31. Lets Learn MoreNow that youve designed your own API,lets talk design again and well start with URLsWe only need two base URLs per resource.31 32. Harolds Dogs API32ResourcePOSTcreateGETreadPUTupdateDELETEdelete/dogs/dogs/{dogId}Create anew dog {dogId}ErrorList dogsGet a dogIf not existsthen errorError ErrorUpdate dogIf not existsthen errorDelete dogIf not existsthen error* Resist the temptation to use verbs for such things as making yourdog run for example: /dogs/{dogId}/setDogToRunningInPark 33. Good, Bad & Ugly Good Bad Ugly33NounsVerbs (slippery slope)/dogs/1234/SetDogToRunningStateInPark Instead, update properties using PUT 34. Plurals or Singulars? Dog vs Dogs Owner vs Owners Leash vs Leashes Choose one! Consistency please Ancestry standard is plurals34 35. Abstract or concrete naming?35 36. Abstract to Concrete Continuum Super High High Medium Low/things/animals/dogs/labrador 37. Concrete is better than abstract.37/dogs 38. What about associations?38GET /owners/5678/dogsPOST /owners/5678/dogs 39. What about complex variations?39 40. Lets Hide Complexity40 41. Hiding the Complexity41PUT (update) like this:PUT /dogs/1234BrownyardRunning 42. Other Stuff42 43. Versioning Standard43 Terracotta Warriors 1st Emperor of China (210 BCE)- 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses- Each face unique Required Facebooks Exp Major Versions Only Rare Minor changes OK- Additive- Robustness Principle 44. Versioning Standard44Versioning Examples:Github.comAccept: application/vnd.github.v3+jsonOdesk.com"Accept: application/vnd.odesk.api-v1+jsonFamilySearch.orgAccept: application/x-fs-v1+jsonPivotallabs.comAccept: application/vnd.github[.version].param[+json]David ZuelkeAccept: application/vnd.com.myservice.v2+xml Ancestry Versioning External Standard (public facing): place version in url on far left- /v1/dogs/{dogId} Internal Standard- Accept Header: accept: application/[component Id].v3+json 45. Other Standards45 Pagination: ?page=1&rows=100LinkedIn: start + countGoogle: (#s are one start based)+ num (nextpage)Facebook: offset + limitTwitter: page + rppSpring: page + sizeFamilySearch: start + countFaGceitbHouobk: page + per_page/joe.smith/friends?fields=id,name,picture Counting: /v1/dogs/count Casing URLs Lowercase (Service-Tier)Be liberal in what you accept and conservative in what you send Properties PascalCase (language agnostic) Searching: /v1/dogs/search POST body Partial Response: ?fields=name,description,ageGoogle?fields=title,media:group(media:thumbnail) 46. 46Use 2 base URLsUse HTTPverbs CRUDDoggone ya,use NounsOh, and hide thecomplexityRESTSummation 47. Client Proxy StandardsStandards for client proxy47 48. Single Request & Response Use Wrapper Classes Helps with versioning Naming Standard Method name followed by "Request"or "Response" ExampleGetDogResponse response =GetDog(GetDogRequest request);48 49. 49Hi, myname is Dugpublic class Dog{long DogId,string Name, Dugstring Description,enum Colorstring Owner Masterenum ActivityStatebool TailStateetc}Request & Response Objects 50. Method Naming Use Full Words Start with a Verb End with a Noun Use CRUD verbs only:- Get, Add, Update, Delete Use Namespacing to Organize Your API Dogs.GetDogs() Dogs.AddDog(addDogRequest request) Owners.GetDogs()50 51. Service Naming Use Full Words Limit Name to 2 Words Users Trees Navigation Records Bad to GoodOREM Record Corrections51 52. Proxy Guidelines Design interfaces from the clients perspective An API design should make using it very obvious Design as a group Two heads are usually better than one Remember: Good designs take time - and it's worth it! Take the time to make good decisions52 53. Golly, use fullwords will ya?53Forget yur CRUD verbs(followed by a noun) and you mightas well forget your can of worms.Shucks, useNamespacing!Yeah, service names aintbut one word. LikeUsers, Trees, Search, EtcProxySummation 54. Sum It UpLets review what weve talked about54 55. Lets Design a Trees API(your family tree)55 56. 56ResourcePOSTcreateGETreadPUTupdateDELETEdeleteLets Use This Chart Again 57. Lets Fill In The Chart Together57 58. Harolds Trees API58ResourcePOSTcreateGETreadPUTupdateDELETEdelete/trees/trees/{treeId}Create anew tree {treeId}ErrorList trees(only those Iown or shared)Get a treeIf not existsthen errorError ErrorUpdate treeIf not existsthen errorDelete treeIf not existsthen error* Resist the temptation to use verbs for such things as making yourtree public for example: /trees/{treeId}/makeMyTreePublic 59. What We Have Learned Keep Developer In Mind Keep It Simple & Obvious Be Consistent Design as a Group REST APIs Use Nouns Use HTTP Verbs (CRUD) 2 URLs per Resource only Hide the Complexity59 Proxies Full words CRUD Verbs Followed by Noun NamespaceingResourcePOSTcreateGETreadPUTupdateDELETEdelete 60. ReputationRemember, this is Your API.Your name is on it.This is your reputation riding on the line.Will Engineers thank you each day they go to work?60 61. Thank youNow Go Design Something Great!