api design antipatterns - apicon sf

79
API Antipatterns …identifying, and avoiding them Manish Pandit mpandit@ netflix.com lobster1234

Post on 19-Oct-2014

302 views

Category:

Technology


3 download

DESCRIPTION

APIs have become a part of the product ecosystem - and help the businesses by extending their developer base, and offering seamless integration with other services or products. Sometimes, the APIs themselves are the product. However, with so many APIs around, patterns emerge. Patterns are repeatable, reusable solutions to commonly occurring problems. Where there are patterns, there are also antipatterns. While APIs are not a new paradigm - there are no set standards or specifications formed by a committees or governing bodies for APIs. On top of this, the APIs are often built at various stages of the product, and have a good chance of being disjoint as more are added. In this talk Netflix engineers will discuss various antipatterns that creep into the API design and implementation, and how to identify and avoid them. They will also share their experiences with building APIs. While the antipatterns do not pose as big a functional challenge, they can and do impact integration efforts, scalability and performance among other things. After this session, you should be able to get familiar with the best practices around solving the most common patterns, and make your engineers and API consumers happy!

TRANSCRIPT

API Design Antipatterns

API Antipatternsidentifying, and avoiding themManish [email protected]

APIs

APIsA means for software to interact with other software.

Protocol

ProtocolMay or may not be standard

ProtocolMay or may not be standard

Indicates an agreement between the parties

Payload

Payload

Data Format

XML

JSON

Custom Text

Binary

Payload

Transport mechanism

HTTP

SMTP

Custom Text-based

Raw socketsHTTP Request httpHTTP Request http://www.netflix.comHTTP Request http://www.netflix.com/headerHTTP Request http://www.netflix.com/header/netflix_logo.gif

HTTP Request http://www.netflix.com/header/netflix_logo.gif

Or, getting a resource from the server by giving its location.Every request has a response.HTTP ResponseHeadersDescribing the response

HTTP ResponseHeadersDescribing the responseStatus CodeIndicating the success/failure

HTTP ResponseHeadersDescribing the responseStatus CodeIndicating the success/failureBodyThe data we asked for

REST APIREST is not a standard, but an architecture REST APIREST is not a standard, but an architecture,which uses HTTP as a model for all interactions.REST APINoun Resource, or the Entity

Verb ActionPatterns

Patterns

Patterns are re-usable solutions to commonly occurring problems.Patterns

They are identified by humans who write code the API as well as the client.Common ScenariosGetting data from the server25Common ScenariosSending data to the server26

AntipatternsAntipatterns are re-usable solutions to commonly occurring problems

Antipatterns....which look great on the surface but they really arent

HTTP Response CodesHTTP 200 OK

{ success : false }HTTP Response CodesHTTP 200 OK

{ error : Person abc not found }HTTP Response CodesThere are more codes than 200 and 5002xx for success3xx for redirects/caching4xx for request/client errors5xx for server errorsalso, the client does not need to see your exception trace

HTTP Response CodesReturn after a delete? 204Failed database constraint? 409Method not supported? 405Trying to ask for too much data? 413Query Strings/pets?name=scruffyQuery Strings/pets?name=scruffy

/pets/name/scruffyQuery StringsAvoid query strings for resource identificationQuery StringsAvoid query strings for resource identification

But use them for request metadataQuery StringsRequest MetadataPaginationFilteringSortingQuery Stringshttp://some.api.com/movies?start=0&count=10&sortBy=name&fields=name,cast,releaseDateMethodsDo not use GET for all readsHEAD to get headers (mostly used for caching)OPTIONS

Do not use POST for all writesPOST to create, or upsertPUT to updateDELETE to deleteResources vs. CollectionsA collection holds similar resourcesmoviesaccountspersonsResources vs. CollectionA path should identify a resource (or resources) in a collection of said resourcesResources vs. Collections/movies/name/{name}

/users/1234

/devices/type/bdplayersResources vs. CollectionAlways specify a qualifier in the path when accessing resource(s) in a collectionResources vs Collectionexcept when accessing via the primary IDResources vs CollectionAlways think about the path to the resource.

///value

And manipulate it with the verbsResourcesAlso, the properties of the resource can also be a part of the path.

/movies/rating/GAuthentication401 UnauthorizedAuthentication403 ForbiddenAuthenticationUse HTTP 401 to indicate that the client needs to authenticateAuthenticationUse HTTP 401 to indicate that the client needs to authenticateUse HTTP 403 to indicate that the credentials the client holds do not allow access to the said resource(s).401 vs 403401 = Come back with a key

403 = Your key does not work for this lock.Resources in an Island Every entity or a resource is tied to others.

Resources in an Island When youre stuck guessing the connections of a resource.Resources in an Island HATEOASResources in an Island HATEOAS(or something similar)Resource DiscoveryAlways have your resources discoverable..via code

Resource DiscoverySo we talked a lot about discoverability and islands..Resource DiscoveryBut where do we start?Resource DiscoveryMeta pages for resources

//metaOr/metaAsync OperationsFor when synchronous calls just will not work Async OperationsHTTP 202 Accepted

Butwhat about the response?

Async OperationsResponse should help the caller..remember?

{statusUrl: }Updates vs. DeletesEverything works when there is data..but what when there is no data..?Updates vs. DeletesHTTP PUT to set a value to null?Updates vs. DeletesHTTP DELETE to set a value to null?

(Remember, we have a path to not just the resource..)Updates vs. DeletesDELETE /movies//rating Data feedsWhats an API that does not syndicate..Data feedsThink nasty batch jobs sucking the catalog nightly!Data feedsRequest metadata to the rescue?Data feedsRequest metadata to the rescue?

.how about a ?since=1d

or ?since=UTCStateThey said REST is statelessbut is it?StateStateless == SimpleStateState sits only on the serverRequests either change the state, or get it.All requests see the same state of the resource

StateBut what about cookies?StateAvoid cookies!

Use tokens instead. Let the client figure out to store it as a cookie for convinience.Accept cookies as a fallback, but prefer a query parameter or HTTP request header.

More topics..VersioningUsing 301s to redirect/retire APIsCachingUsing HTTP headers correctlyCaching response bodiesRFC 2616Questions