1、M A N N I N GJJ GeewaxForeword by Jon SkeetTopicThis topic covers.Resource identificationHow to identify resources in an APIStandard methodsThe set of standard methods for use in resource-oriented APIsPartial updates and retrievalsHow to interact with portions of resourcesCustom methodsUsing custom(
2、non-standard)methods in resource-oriented APIsLong-running operationsHow to handle methods that are not instantaneousRerunnable jobsRunning repeated custom functionality in an APISingleton sub-resourcesIsolating portions of resource data Cross referencesHow to reference other resources in an APIAsso
3、ciation resourcesHow to manage many-to-many relationships with metadataAdd and remove custom methodsHow to manage many-to-many relationships without metadataPolymorphismDesigning resources with dynamically-typed attributesCopy and moveDuplicating and relocating resources in an APIBatch operationsExt
4、ending methods to apply to groups of resources atomicallyCriteria-based deletionDeleting multiple resources based on a set of filter criteriaAnonymous writesIngesting unaddressable data into an APIPaginationConsuming large amounts of data in bite-sized chunksFilteringLimiting result sets according t
5、o a user-specified filterImporting and exportingMoving data into or out of an API by interacting directly with a storage systemVersioning and compatibilityDefining compatibility and strategies for versioning APIsSoft deletionMoving resources to the“API recycle bin”Request deduplicationPreventing dup
6、licate work due to network interruptions in APIsRequest validationAllowing API methods to be called in“safe mode”Resource revisionsTracking resource change historyRequest retrialAlgorithms for safely retrying API requestsRequest authenticationVerifying that requests are authentic and untampered with
7、API Design PatternsAPI DesignPatternsJJ GEEWAXFOREWORD BY JON SKEETMANNINGSHELTER ISLANDFor online information and ordering of this and other Manning books,please .The publisher offers discounts on this book when ordered in quantity.For more information,please contactSpecial Sales DepartmentManning
8、Publications Co.20 Baldwin RoadPO Box 761Shelter Island,NY 11964Email:2021 by Manning Publications Co.All rights reserved.No part of this publication may be reproduced,stored in a retrieval system,or transmitted,in any form or by means electronic,mechanical,photocopying,or otherwise,without prior wr
9、itten permission of the publisher.Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks.Where those designations appear in the book,and Manning Publications was aware of a trademark claim,the designations have been printed in initial caps
10、or all caps.Recognizing the importance of preserving what has been written,it is Mannings policy to have the books we publish printed on acid-free paper,and we exert our best efforts to that end.Recognizing also our responsibility to conserve the resources of our planet,Manning booksare printed on p
11、aper that is at least 15 percent recycled and processed without the use of elemental chlorine.Development editor:Christina TaylorTechnical development editor:Al KrinkerManning Publications Co.Review editor:Ivan Martinovic 20 Baldwin RoadProduction editor:Deirdre S.HiamPO Box 761Copy editor:Michele M
12、itchellShelter Island,NY 11964Proofreader:Keri HalesTechnical proofreader:Karsten StrbkTypesetter:Dennis DalinnikCover designer:Marija TudorISBN:9781617295850Printed in the United States of America To Kai and Luca.You are awesome.viibrief contentsPART 1INTRODUCTION.11Introduction to APIs32Introducti
13、on to API design patterns14PART 2DESIGN PRINCIPLES.313Naming334Resource scope and hierarchy475Data types and defaults65PART 3FUNDAMENTALS.856Resource identification877Standard methods1048Partial updates and retrievals1229Custom methods14110Long-running operations15411Rerunnable jobs175BRIEF CONTENTS
14、viiiPART 4RESOURCE RELATIONSHIPS.18712Singleton sub-resources18913Cross references20014Association resources20715Add and remove custom methods21816Polymorphism225PART 5COLLECTIVE OPERATIONS.23717Copy and move23918Batch operations25419Criteria-based deletion27020Anonymous writes27821Pagination28522Fi
15、ltering29923Importing and exporting313PART 6SAFETY AND SECURITY.33324Versioning and compatibility33525Soft deletion35726Request deduplication37127Request validation38328Resource revisions39029Request retrial40530Request authentication416ixcontentsforewordxxiprefacexxiiiacknowledgmentsxxvabout this b
16、ookxxviiabout the authorxxxiiiabout the cover illustrationxxxivPART 1INTRODUCTION.11 Introduction to APIs31.1What are web APIs?31.2Why do APIs matter?51.3What are resource-oriented APIs?61.4What makes an API“good”?8Operational9Expressive9Simple10Predictable122 Introduction to API design patterns142.
17、1What are API design patterns?142.2Why are API design patterns important?17CONTENTSx2.3Anatomy of an API design pattern19Name and synopsis19Motivation19Overview20Implementation21Trade-offs212.4Case study:Twapi,a Twitter-like API22Overview22Listing messages23Exporting data26PART 2DESIGN PRINCIPLES.31
18、3 Naming333.1Why do names matter?343.2What makes a name“good”?34Expressive35Simple35Predictable363.3Language,grammar,and syntax36Language37Grammar37Syntax403.4Context413.5Data types and units413.6Case study:What happens when you choose bad names?433.7Exercises454 Resource scope and hierarchy474.1Wha
19、t is resource layout?48Types of relationships49Entity relationship diagrams524.2Choosing the right relationship54Do you need a relationship at all?54References or in-line data55Hierarchy574.3Anti-patterns59Resources for everything59Deep hierarchies61In-line everything634.4Exercises645 Data types and
20、 defaults655.1Introduction to data types66Missing vs.null675.2Booleans68CONTENTSxi5.3Numbers69Bounds70Default values71Serialization715.4Strings73Bounds73Default values74Serialization755.5Enumerations765.6Lists77Atomicity77Bounds78Default values795.7Maps79Bounds82Default values825.8Exercises82PART 3F
21、UNDAMENTALS.856 Resource identification876.1What is an identifier?876.2What makes a good identifier?88Easy to use88Unique88Permanent89Fast and easy to generate89Unpredictable90Readable,shareable,and verifiable90Informationally dense916.3What does a good identifier look like?91Data type91Character se
22、t92Identifier format92Checksums93Resource type93Hierarchy and uniqueness scope946.4Implementation95Size95Generation96Tomb-stoning98Checksum98Database storage1006.5What about UUIDs?1016.6Exercises1027 Standard methods1047.1Motivation1057.2Overview1057.3Implementation106Which methods should be support
23、ed?106Idempotence and side effects107Get108List109Create112CONTENTSxiiUpdate114Delete115Replace116Final API definition1187.4Trade-offs1207.5Exercises1208 Partial updates and retrievals1228.1Motivation123Partial retrieval123Partial update1238.2Overview1258.3Implementation128Transport128Maps and neste
24、d interfaces129Repeated fields132Default values133Implicit field masks135Updating dynamic data structures136Invalid fields137Final API definition1388.4Trade-offs138Universal support139Alternative implementations1398.5Exercises1409 Custom methods1419.1Motivation142Why not just standard methods?1429.2
25、Overview1459.3Implementation146Side effects147Resources vs.collections147Stateless custom methods149Final API definition1519.4Trade-offs1529.5Exercises15210 Long-running operations15410.1Motivation15510.2Overview15610.3Implementation158What does an LRO look like?159Resource hierarchy160Resolution160
26、Error handling164Monitoring progress165Canceling operations167Pausing and resuming operations168Exploring operations169Persistence170Final API definition172CONTENTSxiii10.4Trade-offs17310.5Exercises17411 Rerunnable jobs17511.1Motivation17611.2Overview17611.3Implementation178Job resources178The custo
27、m run method180Job execution resources181Final API definition18411.4Trade-offs18611.5Exercises186PART 4RESOURCE RELATIONSHIPS.18712 Singleton sub-resources18912.1Motivation189Why should we use a singleton sub-resource?19012.2Overview19112.3Implementation192Standard methods192Resetting195Hierarchy195
28、Final API definition19612.4Trade-offs197Atomicity198Exactly one sub-resource19812.5Exercises19813 Cross references20013.1Motivation20013.2Overview20113.3Implementation202Reference field name202Data integrity203Value vs.reference204Final API definition20613.4Trade-offs20613.5Exercises206CONTENTSxiv14
29、 Association resources20714.1Motivation20714.2Overview208Association alias methods20914.3Implementation210Naming the association resource210Standard method behavior210Uniqueness211Read-only fields211Association alias methods212Referential integrity213Final API definition21414.4Trade-offs216Complexit
30、y216Separation of associations21614.5Exercises21615 Add and remove custom methods21815.1Motivation21915.2Overview21915.3Implementation220Listing associated resources220Data integrity221Final API definition22215.4Trade-offs223Nonreciprocal relationship223Relationship metadata22315.5Exercises22416 Pol
31、ymorphism22516.1Motivation22516.2Overview22616.3Implementation227Deciding when to use polymorphic resources227Polymorphic structure228Polymorphic behavior232Why not polymorphic methods?233Final API definition23416.4Trade-offs23516.5Exercises235CONTENTSxvPART 5COLLECTIVE OPERATIONS.23717 Copy and mov
32、e23917.1Motivation24017.2Overview24017.3Implementation241Identifiers241Child resources244Related resources245External data247Inherited metadata249Atomicity250Final API definition25217.4Trade-offs25217.5Exercises25318 Batch operations25418.1Motivation25518.2Overview25518.3Implementation256Atomicity25
33、6Operation on the collection257Ordering of results258Common fields258Operating across parents259Batch Get261Batch Delete263Batch Create264Batch Update265Final API definition26618.4Trade-offs26918.5Exercises26919 Criteria-based deletion27019.1Motivation27119.2Overview27119.3Implementation272Filtering results272Validation only by default274Result count275Result sample set275Consistency276Final API d