├── .gitignore ├── favicon.ico ├── _media └── psa-logo.png ├── _sidebar.md ├── examples ├── asynchronism │ ├── polling.png │ └── webhooks.png ├── caching │ └── cache-decision-tree.png └── pagination │ └── paginating-dynamic-data.png ├── .nojekyll ├── references.md ├── README.md ├── index.html ├── LICENSE └── api-style-guide.md /.gitignore: -------------------------------------------------------------------------------- 1 | /.project 2 | -------------------------------------------------------------------------------- /favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stellantis/api-standards/HEAD/favicon.ico -------------------------------------------------------------------------------- /_media/psa-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stellantis/api-standards/HEAD/_media/psa-logo.png -------------------------------------------------------------------------------- /_sidebar.md: -------------------------------------------------------------------------------- 1 | 2 | * [Home](README.md) 3 | * [API Design Guidelines](api-style-guide.md) 4 | * [References](references.md) 5 | -------------------------------------------------------------------------------- /examples/asynchronism/polling.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stellantis/api-standards/HEAD/examples/asynchronism/polling.png -------------------------------------------------------------------------------- /examples/asynchronism/webhooks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stellantis/api-standards/HEAD/examples/asynchronism/webhooks.png -------------------------------------------------------------------------------- /examples/caching/cache-decision-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stellantis/api-standards/HEAD/examples/caching/cache-decision-tree.png -------------------------------------------------------------------------------- /examples/pagination/paginating-dynamic-data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stellantis/api-standards/HEAD/examples/pagination/paginating-dynamic-data.png -------------------------------------------------------------------------------- /.nojekyll: -------------------------------------------------------------------------------- 1 | prevents GitHub Pages from ignoring files that begin with an underscore (needed for some 'docsify' features - https://docsify.js.org/#/quickstart?id=writing-content) -------------------------------------------------------------------------------- /references.md: -------------------------------------------------------------------------------- 1 | * [Representational State Transfer (REST)](https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm) by Fielding, R. 2 | * [Hypertext Transfer Protocol (HTTP/1.1) - RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231) 3 | * [REST Cookbook](http://restcookbook.com) 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Groupe PSA API standards 2 | 3 | Standards and guidelines for Groupe PSA REST APIs. 4 | * [API Design Guidelines](api-style-guide.md) 5 | * [References](references.md) 6 | 7 | # License 8 | 9 | Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License. 10 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 20 | 21 | 22 |
23 | 24 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above MAY be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor MAY not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | MAY not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it MAY be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it MAY be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | -------------------------------------------------------------------------------- /api-style-guide.md: -------------------------------------------------------------------------------- 1 | 2 | # Groupe PSA API Design Guidelines 3 | 4 | ## Introduction 5 | 6 | This repository provides guidelines and examples for APIs at PSA. These guidelines intend to encourage consistency, maintainability, and best practices across all APIs and applications. 7 | 8 | These guidelines were strongly inspired from Paypal's API Standards and some other [references](references.md). 9 | 10 | ## Document Semantics, Formatting, and Naming 11 | 12 | The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119](https://www.ietf.org/rfc/rfc2119.txt). 13 | 14 | # Contract Description 15 | 16 | ## OpenAPI 17 | 18 | The [OpenAPI specification](https://swagger.io/specification/) (formerly known as the Swagger Specification) is a powerful definition format to describe RESTful APIs. All REST APIs PSA MUST be defined using this format. As it is both human and machine readable, Swagger is the essential link between any unit involved in an API's lifecycle, starting from business & technical specifications, to deployment. 19 | 20 | As shown in the [official documentation](https://swagger.io/docs/specification/2-0/basic-structure/), a sample Swagger specification written in YAML (as opposed to JSON) looks like this : 21 | 22 | ```yaml 23 | swagger: "2.0" 24 | info: 25 | title: Sample API 26 | description: API description in YAML. 27 | version: 1.0.0 28 | 29 | host: api.example.com 30 | basePath: /v1 31 | schemes: 32 | - https 33 | 34 | paths: 35 | /users: 36 | get: 37 | summary: Returns a list of users. 38 | description: Optional extended description in Markdown. 39 | produces: 40 | - application/json 41 | responses: 42 | 200: 43 | description: OK 44 | ``` 45 | 46 | ### Mandatory step towards deployment 47 | 48 | IBM API Connect, PSA's API manager, natively interfaces with Swagger, meaning a well designed Swagger heavily accelerates the API's publication process. Before submitting an REST API for deployment, conception/development teams MUST : 49 | * Provide a Swagger file describing the API 50 | * Ensure the file reflects its implementation 51 | * Ensure the file file contains all of the information required for publication. 52 | 53 | # HTTP Protocol 54 | 55 | ## Allowed HTTP Verbs List 56 | 57 | HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are `POST`, `GET`, `PUT`, `PATCH` and `DELETE`. There are a number of other verbs, too, but are utilized less frequently. All APIs MUST only use the verbs listed in the table below. 58 | 59 | | Method | Action | 60 | |-----------|---------------------------------------------------------------------------------------------------| 61 | | `POST` | Method requests the server to **create** a resource in the database | 62 | | `GET` | Method **requests data** from the resource and should not produce any side effect | 63 | | `PUT` | Method requests the server to **update** resource or **create** the resource, if it doesn’t exist | 64 | | `PATCH` | Method requests the server to **partially update** resource | 65 | | `DELETE` | Method requests that the resources, or its instance, **should be removed** from the database | 66 | 67 | ## Idempotent & Safe 68 | 69 | ### Idempotency 70 | 71 | Idempotency is an important aspect of building a fault-tolerant API. Idempotent APIs enable clients to safely retry an operation without worrying about the side-effects that the operation can cause. For example, a client can safely retry an idempotent request in the event of a request failing due to a network connection error. 72 | 73 | Per [HTTP Specification](https://tools.ietf.org/html/rfc2616#section-9.1.2), a method is idempotent if the side-effects of more than one identical requests are the same as those for a single request. Methods `GET`, `HEAD`, `PUT` and `DELETE` are defined idempotent. 74 | 75 | **Example** - The following statement is **idempotent** : no matter how many times this statement is executed, the customer’s age will always be set to 20. 76 | 77 | ```properties 78 | customer.age = 20 // idempotent 79 | ``` 80 | 81 | **Example** - The following statement is **not idempotent** : executing this 10 times will result in different outcomes. 82 | 83 | ```properties 84 | customer.age += 1 // non-idempotent 85 | ``` 86 | 87 | ### Safe 88 | 89 | Per [HTTP Semantics and Content](https://tools.ietf.org/html/rfc7231#page-22) request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource. Likewise, reasonable use of a safe method is not expected to cause any harm, loss of property, or unusual burden on the origin server. 90 | 91 | Safe methods are HTTP methods that do not modify resources. Meaning safe HTTP method MUST NOT create, update or delete resources. In addition, safe methods can be cached and prefetched without any repercussions to the resource. 92 | 93 | **Example** - The following request is **incorrect** if this request actually deletes the resource : `GET` methods SHALL NOT produce any side effect 94 | 95 | ```log 96 | GET https://dev.api.inetpsa.com/project/customers/9812763/delete HTTP/1.1 97 | ``` 98 | 99 | ### Summary Table 100 | 101 | The table below should be read as follows : 102 | * `GET` 103 | * MUST NOT create any side-effect (safe) 104 | * More than one identical requests MUST have the same behavior (idempotent) 105 | * `POST` 106 | * MAY create side-effect (not safe) 107 | * MAY behave differently when performing identical requests (not idempotent) 108 | * `PUT` 109 | * MAY create side-effects (not safe) 110 | * More than one identical requests MUST have the same behavior (idempotent) 111 | * `PATCH` 112 | * MAY create side-effect (not safe) 113 | * MAY behave differently when performing identical requests (not idempotent) 114 | * `DELETE` 115 | * MAY create side-effects (not safe) 116 | * More than one identical requests MUST have the same behavior (idempotent) 117 | 118 | | |Idempotent |Safe | 119 | |-----------|-----------|-----------| 120 | |`GET` |**Yes** |**Yes** | 121 | |`POST` |No |No | 122 | |`PUT` |**Yes** |No | 123 | |`PATCH` |No |No | 124 | |`DELETE` |**Yes** |No | 125 | 126 | ## Status codes 127 | 128 | Per [RF7231](https://www.ietf.org/rfc/rfc2616.txt), the Status-Code element is a 3-digit integer result code of the attempt to understand and satisfy the request. 129 | 130 | ### Status Codes Ranges 131 | 132 | The first digit of the Status-Code defines the class of response. The last two digits do not have any categorization role. There are 5 values for the first digit: 133 | - `1xx`: Informational - Request received, continuing process 134 | - `2xx`: Success - The action was successfully received, understood, and accepted 135 | - `3xx`: Redirection - Further action must be taken in order to complete the request 136 | - `4xx`: Client Error - The request contains bad syntax or cannot be fulfilled 137 | - `5xx`: Server Error - The server failed to fulfill an apparently valid request. (**note** : API developers MUST NOT explicitly return `5xx` codes as it is taken care by the server itself) 138 | 139 | ### Status Codes List 140 | 141 | It is RECOMMENDED that APIs only return the most commonly used status codes listed in the table below. APIs MAY return a status code that is not defined in this table, in which case API designers must clearly state the reasons behind this choice. However, APIs MUST NOT return a status code that is not listed in the [HTTP/1.1 - RFC2616](https://www.ietf.org/rfc/rfc2616.txt). 142 | 143 | | Status Code | Description | 144 | |-------------|-------------| 145 | | `200 OK` | Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action. | 146 | | `201 Created` | The request has been fulfilled and resulted in a new resource being created. Successful creation occurred (via either POST or PUT). Set the Location header to contain a link to the newly-created resource (on POST). Response body content may or may not be present. | 147 | | `202 Accepted` | Used for asynchronous method execution to specify the server has accepted the request and will execute it at a later time. For more details, please refer [Asynchronous Operations](#performance--asynchronism). | 148 | | `204 No Content` | The server successfully processed the request, but is not returning any content. The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields. | 149 | | `304 Not Modified` | Used for conditional GET calls to reduce band-width usage. If used, must set the Date, Content-Location, ETag headers to what they would have been on a regular GET call. There must be no body on the response.| 150 | | `400 Bad Request` | The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.| 151 | | `401 Unauthorized` | The request requires authentication and none was provided or the provided one is invalid and authentication should be tried again. Note the difference between this and `403 Forbidden`.| 152 | | `403 Forbidden` | The server understood the request, but is refusing to fulfill it. It SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead | 153 | | `404 Not Found` | Used when the requested resource is not found, whether it doesn't exist or if there was a 401 or 403 that, for security reasons, the service wants to mask | 154 | | `406 Not Acceptable` | The server MUST return this status code when it cannot return the payload of the response using the media type requested by the client. For example, if the client sends an `Accept: application/xml` header, and the API can only generate `application/json`, the server MUST return `406`. | 155 | | `415 Unsupported Media Type` | The server MUST return this status code when the media type of the request's payload cannot be processed. For example, if the client sends a `Content-Type: application/xml` header, but the API can only accept `application/json`, the server MUST return `415`. | 156 | | `429 Too Many Requests` | The server return this status code when the user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes.| 157 | | `500 Internal Server Error` | This is either a system or application error, and generally indicates that although the client appeared to provide a correct request, something unexpected has gone wrong on the server. A `500` response indicates a server-side software defect or site outage. `500` SHOULD NOT be utilized for client validation or logic error handling. | 158 | | `503 Service Unavailable` | The server is unable to handle the request for a service due to temporary maintenance. | 159 | 160 | ### HTTP Method to Status Code Mapping 161 | 162 | For each HTTP method, API developers SHOULD use only status codes marked as "X" in this table. 163 | 164 | | Status Code | 200 Success | 201 Created |202 Accepted | 204 No Content | 400 Bad Request | 401 Unauthorized | 403 Forbidden| 404 Not Found |500 Internal Server Error | 165 | |-------------|:------------|:------------|:------------|:---------------|:----------------|:----------------|:----------------|:---------------|:------------------------| 166 | | `GET` | X | | | | X | X | X | X | X | 167 | | `POST` | X | X | | X | X | X | X | | X | 168 | | `PUT` | X | | X | X | X | X| X | X | X | 169 | | `PATCH` | X | | | X | X | X| X | X | X | 170 | | `DELETE` | X | | | X | X | X| X | X | X | 171 | 172 | 173 | * `GET`: The purpose of the `GET` method is to retrieve a resource. On success, a status code `200` and a response with the content of the resource is expected. In cases where resource collections are empty (0 items in `/customers`), `200` is the appropriate status (resource will contain an empty `items` array). `204` SHALL NOT be used even though there is no content. 174 | 175 | * `POST`: The primary purpose of `POST` is to create a resource. If the resource did not exist and was created as part of the execution, then a status code `201` SHOULD be returned. 176 | * It is expected that on a successful execution, a reference to the resource created (in the form of a link or resource identifier) is returned in the response body. 177 | * Idempotency semantics: If this is a subsequent execution of the same invocation and the resource was already created, then a status code of `200` SHOULD be returned. For more details on idempotency in APIs, refer to [idempotency](#idempotent). 178 | 179 | * `PUT`: This method SHOULD return status code `204` as there is no need to return any content in most cases as the request is to update a resource and it was successfully updated. The information from the request should not be echoed back. 180 | 181 | * `PATCH`: This method SHOULD follow the same status/response semantics as `PUT`, `204` status and no response body. 182 | * `200` + response body should be avoided at all costs, as `PATCH` performs partial updates, meaning multiple calls per resource is normal. As such, responding with the entire resource can result in large bandwidth usage, especially for bandwidth-sensitive mobile clients. 183 | 184 | * `DELETE`: This method SHOULD return status code `204` as there is no need to return any content in most cases as the request is to delete a resource and it was successfully deleted. 185 | * As the `DELETE` method MUST be idempotent as well, it SHOULD still return `204`, even if the resource was already deleted. Usually the API consumer does not care if the resource was deleted as part of this operation, or before. This is also the reason why `204` instead of `404` should be returned. 186 | 187 | # Payload 188 | 189 | ## General JSON Guidelines 190 | 191 | ### JSON Object Key 192 | 193 | A JSON key or attribute MUST : 194 | * Be unique for any given level of data 195 | * Use consistent case for keys : JSON keys MUST be formatted using `camelCase` 196 | * Respect the informational context by using clear and explicit naming : keys MUST use generic terms reusable in a different context than the application it was first designed for 197 | 198 | - **Bad - Non-unique keys at the root of the object** 199 | 200 | ```json 201 | "customer" : { 202 | "id": 19083974, 203 | "name": "John", 204 | "name": "Doe", // Bad : using name twice on the same level of data is forbidden 205 | } 206 | ``` 207 | 208 | - **Good - Unique keys at any given level of data** 209 | 210 | ```json 211 | "customer" : { 212 | "id": 19083974, 213 | "name": "John Doe", 214 | "address": { 215 | "name": "Home", // Good: this is allowed since it belongs to address and not customer 216 | "city": "Paris" 217 | } 218 | } 219 | ``` 220 | 221 | - **Bad - Non generic naming** 222 | 223 | ```json 224 | "customer" : { 225 | "customerId": 19083974, // Bad : since a customer could be a different object in a different context 226 | "homeAddress" : { // Bad : not developer friendly as other projects might call it differently 227 | "city":"Paris" 228 | } 229 | } 230 | ``` 231 | 232 | - **Good - Generic naming** 233 | 234 | ```json 235 | "customer" : { 236 | "id": 19083974, // Good: generic naming, can be used in any context 237 | "address": { // Good : generic naming 238 | "name": "Home", // Good : better naming strategy 239 | } 240 | } 241 | ``` 242 | 243 | ## JSON Types 244 | 245 | This section provides guidelines related to usage of [JSON primitive types](#json-primitive) as well as [commonly useful JSON types](#common-types) for address, name, currency, money, country, phone, among other things. APIs MUST follow common formatting rules to insure consistency across all projects. 246 | 247 | ### JSON Primitive Types 248 | 249 | As per [draft-04](https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5) JSON Schema defines seven primitive types for JSON values: 250 | * **array** : A JSON array. 251 | * **boolean** : A JSON boolean. 252 | * **integer** : A JSON number without a fraction or exponent part. 253 | * **number** : Any JSON number. Number includes integer. 254 | * **null** : The JSON null value 255 | * **object** : A JSON object. 256 | * **string** : A JSON string. 257 | 258 | #### Null 259 | 260 | APIs MUST NOT produce or consume null values. In JSON, a property that doesn't exist or is missing in the object is considered to be `undefined`; this is conceptually separate from a property that is defined with a value of `null`. 261 | 262 | For instance, a property `address` defined as `{"type": "null"}` is represented as : 263 | 264 | ```json 265 | "customer" : { 266 | "id": 19083974, 267 | "address": "null" 268 | } 269 | ``` 270 | 271 | While a property `address` that is `undefined` MUST NOT be present in the object : 272 | 273 | ```json 274 | "customer" : { 275 | "id": 19083974, 276 | } 277 | ``` 278 | 279 | 280 | ### Common Types 281 | 282 | Resource representations in API MUST reuse the common data type definitions below where possible. Following sections provide some details about some of these common types. 283 | 284 | #### Internationalization 285 | 286 | The following common types MUST be used with regard to global country, currency, language and locale. 287 | 288 | | Type | Example | Rule | 289 | |-----------------|---------|------| 290 | | Country code | `FR` | All APIs MUST use the [ISO 3166-1 alpha-2](http://www.iso.org/iso/country_codes.htm) two letter country code standard | 291 | | Currency code | `EUR` | All APIs MUST use the the three letter currency code as defined in [ISO 4217](http://www.currency-iso.org/). For quick reference on currency codes, see [http://en.wikipedia.org/wiki/ISO_4217](http://en.wikipedia.org/wiki/ISO_4217). | 292 | | Language | `fr-FR` | All APIs MUST use the [BCP-47](https://tools.ietf.org/html/bcp47) language tag composed of : the `ISO-639 alpha-2 language code` (Optional), the `ISO-15924` script tag, the `ISO-3166 alpha-2` country code | 293 | 294 | #### Date Time Common Types 295 | 296 | The following common types MUST be used to express various date-time formats: 297 | 298 | | Type | Example | RFC | 299 | |-------------------|------------------------|-----------------------| 300 | | Date & Time | `2018-02-06T19:31:29` | RFC3339 `date-time` | 301 | | Date | `2018-02-06` | RFC3339 `full-date` | 302 | | Time | `19:31:29` | RFC3339 `full-time` | 303 | 304 | #### Geolocated data 305 | 306 | All APIs exposing geolocated data MUST use the open standard format [GeoJSON](https://fr.wikipedia.org/wiki/GeoJSON). As per [RFC7946](https://tools.ietf.org/html/rfc7946), GeoJSON "defines several types of JSON objects and the manner in which they are combined to represent data about geographic features, their properties, and their spatial extents." 307 | 308 | Any of the following geometry type MUST be formatted using GeoJSON : 309 | * **Points & Multipoints** : addresses and locations 310 | 311 | ```json 312 | { 313 | "type": "Feature", 314 | "geometry": { 315 | "type": "Point", 316 | "coordinates": [125.6, 10.1] 317 | }, 318 | "properties": { 319 | "name": "Home Adress" 320 | } 321 | } 322 | ``` 323 | 324 | * **LineStrings & MultiLineStrings** : streets, highways and boundaries 325 | 326 | ```json 327 | { 328 | "type": "Feature", 329 | "geometry": { 330 | "type": "LineString", 331 | "coordinates": [ 332 | [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] 333 | ] 334 | }, 335 | "properties": { 336 | "street": "7th Avenue" 337 | } 338 | }, 339 | ``` 340 | 341 | * **Polygons & MultiPolygons** : countries, provinces, tracts of land 342 | 343 | ```json 344 | { "type": "Feature", 345 | "geometry": { 346 | "type": "Polygon", 347 | "coordinates": [ 348 | [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], 349 | [100.0, 1.0], [100.0, 0.0] ] 350 | ] 351 | }, 352 | "properties": { 353 | "country": "France" 354 | } 355 | }, 356 | ``` 357 | 358 | ## Error Format 359 | 360 | The HTTP status codes in the `4xx` range indicate client-side errors (validation or logic errors), while those in the `5xx` range indicate server-side errors (usually defect or outage). However, these status codes and human readable reason phrase are not sufficient to convey enough information about an error in a machine-readable manner. To resolve an error, non-human consumers of RESTful APIs need additional help. 361 | 362 | ### Error Schema 363 | 364 | An error response MUST include the following fields: 365 | 366 | * `name`: A human-readable, unique name for the error. Should be mapped on the server side to insure consistency. 367 | * `debug`: A unique error identifier generated on the server-side and logged for correlation purposes. 368 | * `message`: A human-readable message, describing the error. This message MUST be a description of the problem NOT a suggestion about how to fix it. 369 | * `link`: [HATEOAS](#hypermedia) links (in HAL format) specific to an error scenario. Use these links to provide more information about the error scenario and how to resolve it. 370 | 371 | An error response MUST NOT include any of the following information : 372 | * Internal code 373 | * File path 374 | * Stack trace 375 | 376 | Therefore, APIs MUST return a JSON error representation that conforms to the the following schema. 377 | 378 | ```json 379 | { 380 | "name":"VALIDATION_ERROR", 381 | "debug":"123456789", 382 | "message":"Invalid data provided", 383 | "link":"http://developer.psa-peugeot-citroen.com/apidoc#VALIDATION_ERROR" 384 | } 385 | ``` 386 | 387 | ## Handling Multiple Formats 388 | 389 | In the case where APIs serve more than one content type, consumers MUST specify type they need using Accept header. 390 | 391 | APIs MAY take as input or output any content type needed (an audio file, a specific text format etc.). Each API endpoint specifies what response type it outputs and what it consumes in cases where it applies (for POST requests for instance) : 392 | 393 | ```log 394 | GET /URL HTTP/1.1 395 | Accept : text/* 396 | ``` 397 | 398 | ```log 399 | HTTP/1.1 200 OK 400 | Content-Type : text/html 401 | ``` 402 | 403 | See complete list of [MIME Types](https://developer.mozilla.org/fr/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types) 404 | 405 | ## Hypermedia 406 | 407 | ### HATEOAS 408 | 409 | Hypermedia, an extension of the term [hypertext](https://en.wikipedia.org/wiki/Hypertext), is a nonlinear medium of information which includes graphics, audio, video, plain text and hyperlinks according to [wikipedia](https://en.wikipedia.org/wiki/Hypermedia). Hypermedia As The Engine Of Application State (`HATEOAS`) is a constraint of the REST application architecture described by Roy Fielding in his [dissertation](https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm). 410 | 411 | In the context of RESTful APIs, a client could interact with a service entirely through hypermedia provided dynamically by the service. A hypermedia-driven service provides representation of resource(s) to its clients to navigate the API dynamically by including hypermedia links in the responses. 412 | 413 | APIs MAY use hypermedia, thought it is not mandatory. APIs using hypermedia MUST however do it using [HAL](#hal). 414 | 415 | ### HAL 416 | 417 | HAL is a simple format that gives a consistent and easy way to hyperlink between resources in your API. For detailed information on HAL refer to this [link](https://stateless.group/hal_specification.html). In short, HAL provides a set of conventions for expressing hyperlinks in either JSON or XML. 418 | 419 | For simplicity reasons, all APIs using HATEOAS along with HAL formatting MUST only use the following properties. 420 | * `_links` : This property contains links related to the current object. For example, a `customer` object using HAL will contain links to the vehicles owned by the user. 421 | * `_embedded` : This property contains commonly related objects to the current object. This property SHALL BE empty. 422 | 423 | #### HAL Examples 424 | 425 | ```log 426 | GET /cars/9837127 HTTP/1.1 427 | ``` 428 | 429 | **Sample car object without using HAL** 430 | 431 | ```json 432 | { 433 | "id" : 9837127, 434 | "model" : "DS3", 435 | "createdAt": "2017-08-10T13:46:39.652+0000", 436 | "updatedAt": "2017-08-10T13:46:39.652+0000", 437 | } 438 | ``` 439 | 440 | **Sample car object using HAL** 441 | 442 | ```json 443 | { 444 | "_links": { 445 | "self": { 446 | "href": "/cars/9837127" 447 | } 448 | ... 449 | }, 450 | "id" : 9837127, 451 | "model" : "DS3", 452 | "createdAt": "2017-08-10T13:46:39.652+0000", 453 | "updatedAt": "2017-08-10T13:46:39.652+0000", 454 | "_embedded": { 455 | "owner": { 456 | "_links": { 457 | "self": { 458 | "href": "/customers/0981233" 459 | } 460 | }, 461 | "id": "0981233", 462 | "name": "John Doe" 463 | } 464 | } 465 | ``` 466 | 467 | For additional examples, please refer to this [list of public hypermedia APIs using HAL](https://github.com/mikekelly/hal_specification/wiki/APIs) 468 | 469 | # URI 470 | 471 | ## URI Structure 472 | 473 | **Example** : API called `factory` under the `manufacturing` domain. This specific endpoint addresses `v1` of the API and accesses the ressource `customers` (filtering by name `John`) 474 | 475 | ```log 476 | https://api-preprod.mpsa.com/manufacturing/factory/v1/customers?name=john 477 | \___/ \___________________/\____________/\______/\_/\________/ \_______/ 478 | | | | | | | | 479 | protocol domain classification api version resource query 480 | environement name parameters 481 | ``` 482 | 483 | APIs at PSA MUST be be formatted with the following components : 484 | - **protocol** : must always be `https` 485 | - **environment** : could be `prod`, `preprod` or `dev` 486 | - **api** : specifies that this specific URI is an API endpoint 487 | - **domain** : specific to PSA, can include a sub domain 488 | - **classification** : may not always be needed in the case of enterprise APIs as opposed to application APIs 489 | - **api name** : the name of the API 490 | - **version** : must only contain the major version (`v1` instead of `v1.0`) 491 | 492 | ## URI Naming Rules 493 | 494 | All API URIs MUST follow the rules listed below : 495 | 1. MUST NOT contain actions or verbs 496 | 2. MUST contain the plural form of resources 497 | 3. MUST use the English language 498 | 4. HTTP methods SHALL define the kind of action to be performed on the resource 499 | 5. MUST be formatted using lower `snake-case` 500 | 6. MUST only contain [UTF-8](https://en.wikipedia.org/wiki/UTF-8#Codepage_layout) encoded characters 501 | 502 | ### Bad way of naming URIs 503 | 504 | Let’s consider a **Customer** resource on which we would like to perform several actions such as `list`, `update`, `delete` and `promote`. The API could be defined in a way that each endpoints corresponds to an operation as follows : 505 | * `GET `**`/getCustomers`** : **return** all customers 506 | * `GET `**`/deleteCustomer`** : **delete** a customer (using `GET` here because we are not sending any data) 507 | * `GET `**`/promoteCustomer`** : **promote** a customer (using `GET` here because we are not sending any data) 508 | * `POST `**`/createCustomer`** : **create** customer according to the request **body** 509 | * `POST `**`/updateCustomer`** : **update** customer according to the request **body** 510 | 511 | **What is wrong with this implementation ?** 512 | 513 | * The API endpoint MUST NOT contain actions or verbs. URIs must contain the plural form of resources and the HTTP method should define the kind of action to be performed on the resource. 514 | * There will be as many endpoints as there are operations to perform and many of these endpoints will contain redundant actions. This leads to unmaintainable APIs. 515 | 516 | ### Good way of naming URIs 517 | 518 | If verbs cannot be used in URIs, how can endpoints tell the server about the actions to be performed on a given resource ? This is where the HTTP methods (or verbs as seen before) play the role. Let's consider the same example following REST rules : 519 | 520 | - **`GET`**`/customers` : **return** all customers 521 | - **`GET`**`/customers/456` : **return** customer with id `456` 522 | - **`POST`**`/customers` : **create** customer according to the request `body` 523 | - **`DELETE`**`/customers/456` : **delete** customer with id `456` 524 | - **`UPDATE`**`/customers/456` : **update** customer with id `456` 525 | - **`GET`**`/companies/123/customers/456` : **return** customer with id #456 in company with id `123` (if we have a resource under a resource) 526 | 527 | Great, but how do we promote (or perform any other specific service using REST)? This is where things get tricky in REST. Since we cannot use verbs in URIs and there is no HTTP method to promote a customer, then how do we do it ? 528 | 529 | There are multiple ways of working around this, choose the one that makes sense to you and to your application. Ask yourself what the `promote` operation does : does it update a field in the user object ? Does it create a new record ? Does it update some kind of resource associated to the user ? Once you have defined the behavior, you can either : 530 | 531 | 1. RESTful way : `PATCH /customers/456` which will partially update the customer object to reflect the promotion (given that your models are built this way) 532 | 2. RESTful way : `PATCH /customers/456/grade` which will partially update a resource called `grade` that is associated to the user 533 | 3. Non-RESTful way though it is clean : `POST /customers/456/promote` this contains a verb and isn't considered RESTful though it is semantically clean and explicit. 534 | 535 | As a rule of thumb, anytime a service (as opposed to a ressource) has to be exposed, APIs MAY expose the result as a resource. 536 | 537 | **Example - Exposing a service to get the average number of trips per car** 538 | 539 | `GET /cars/average-trips` or `GET /cars/trips/average` (depending on how your resources are linked together) 540 | 541 | **What is better with this implementation ?** 542 | 543 | APIs are more **precise** and **consistent**. They are **easier to understand** both for humans and machines and thus **maintainable**. 544 | 545 | ## URI Parameters 546 | 547 | ### Path Parameters 548 | 549 | `/customers/{id}` : variable parts of a URI path, typically used to point to a specific resource within a collection. Each path parameter must be substituted with an actual value when the client makes an API call. 550 | 551 | **Example** : `GET /customers/2097138971` used to target a specific customer resource with ID `2097138971` 552 | 553 | ### Query Parameters 554 | 555 | `/customers?name=value` : appear at the end of the request URI after a question mark (?) separated by ampersands (&). Avoid putting sensitive information (like a password) in query parameters. 556 | 557 | **Example** : `GET /customers?name=John` used to target customers with name `John` 558 | 559 | While these parameters are encrypted over TLS, they can be seen as plain-text in unsafe places like server access logs, bookmarks or referrer headers transmitted to other sites. **Pass sensitive information as HEADER instead**. 560 | 561 | ### Header Parameters 562 | 563 | `X-MyHeader : Value` : an API call may require that custom headers be sent with an HTTP request. Some sample headers are `Content-Type`, `Accept`, `Authorization` etc. 564 | 565 | **Example** : `curl /customers/456 -H "Content-Type: application/xml"` used to retrieve customer `456` in `XML` format 566 | 567 | ### Matrix Parameters 568 | 569 | `/company;name=value/customers` : apply filters to a particular path element. **Matrix params are rarely used** but can be useful in some particular use case, and thus should be kept in mind. 570 | 571 | **Example** : `GET /companies;name=PSA/customers` used to target all customers from company `PSA` 572 | 573 | ## Filtering, Selecting & Sorting 574 | 575 | Reading operations MUST use a `GET` request for reading operations by specifying filters directly in the URL ; as opposed to doing a `POST` filtering using a request body containing the filters. 576 | 577 | ### Filtering 578 | 579 | Filtering allows consumers to only fetch data that matches their conditions. 580 | 581 | - **Single-Value / Single-Criteria Filtering** 582 | `GET /customers?name=John` : get all customers whose names is `John` 583 | 584 | - **Single-Value / Multiple-Criteria Filtering** 585 | `GET /customers?name=John&age=35` : get all customers whose names is `John` **and** age is `35` 586 | 587 | - **Multiple-Value Filtering** 588 | `GET /customers?name=John,Mark` : get all customers whose name is `John` **or** `Mark` 589 | 590 | ### Selecting 591 | 592 | Selecting fields allows consumers to only fetch data they need within a resource. This mechanism is really useful when dealing with bad internet connection. To select fields simply specify them in the URI. 593 | 594 | **Example** : `GET /customers?fields=id,address(city)` only fetch `id` and `address` with `city` only of customer `456` : 595 | 596 | ```json 597 | { 598 | "id": 19083974, 599 | "address":{ 600 | "city": "Paris", 601 | }, 602 | } 603 | ``` 604 | 605 | ### Sorting 606 | 607 | Sorting allows consumers to fetch data in the order they need. The API will respond with the data in the order specified in the request. 608 | 609 | **Examples** : 610 | * `GET /customers?sort=name` fetch all customers and sort by `name` (by default sorting is ascending) 611 | * `GET /customers?sort=name,age` fetch all customers and sort by `name` and `age` 612 | * `GET /customers?sort=age&desc=age` fetch all customers and sort by `age` in `desc` order 613 | 614 | # Pagination 615 | 616 | When the dataset is too large, well designed APIs divide the data set into smaller chunks, which helps in improving the performance and makes it easy for the consumer to handle the response. While there exist several pagination techniques, all APIs MUST use either of the two techniques presented below. 617 | 618 | ## Cursor-based pagination 619 | 620 | This pagination technique is a bit complicated to implement. However, all APIs MUST use this pagination technique when dealing with large data sets and real time data for the reasons explained above. 621 | 622 | **Cursors** let you specify the exact position in the list you want to begin with, as well as the number of items you want to fetch specified using the `limit` parameter (should be set by default). With this technique, no matter how many items were removed or added dynamically to the top of the list, we still have a constant pointer to the exact position where we left off. 623 | 624 | Cursors cannot be used on resource without a monotonically increasing, unique property to sort on. Cursors MUST satisfy all the characteristic below : 625 | - **Unique** : if not unique, conflicts may occur while setting the starting point of the pagination 626 | - **Sortable** : to insure consistency and allow sorting 627 | - **Stateless** : if not stateless, a cursor might not be available by the time it is used 628 | 629 | The ideal cursor is an **encoded timestamp** of the item or its **incremental ID**. 630 | 631 | **Request - Get the first 5 (default limit) items** 632 | 633 | ```log 634 | GET /customers/ HTTP/1.1 635 | ``` 636 | 637 | **Response** 638 | 639 | ```json 640 | { 641 | "data": [0, 1, 2, 3, 4], 642 | "before" : "NDMyNzQyODI3", 643 | "after" : "MTAxNTExOTQ1", 644 | "count": 5, 645 | "total" : 200, 646 | } 647 | ``` 648 | 649 | The following represents the state after the first request : 650 | 651 | ```log 652 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 653 | ^---------->| ^---------->| 654 | before after 655 | NDMyNzQyODI3 MTAxNTExOTQ1 656 | ``` 657 | 658 | **Request - Get the next 5 items** 659 | 660 | GET /customers/cursor=MTAxNTExOTQ1&limit=5 HTTP/1.1 661 | 662 | **Response** 663 | 664 | ```json 665 | { 666 | "data": [5, 6, 7, 8, 9], 667 | "before" : "NDMyNzQyODI3", 668 | "after" : "OPAxODJxKLF4", 669 | "count": 5, 670 | "total" : 200, 671 | } 672 | ``` 673 | 674 | The following represents the state after the second request : 675 | 676 | ```log 677 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 678 | ^---------->| ^---------->| ^--------------->| 679 | before cursor after 680 | NDMyNzQyODI3 MTAxNTExOTQ1 OPAxODJxKLF4 681 | ``` 682 | 683 | ## Offsets pagination 684 | 685 | Using offsets to paginate data is one of the most widely used techniques for pagination. This technique SHALL be used by default. API consumers simply need to specify : 686 | * An `offset` (or `page`): the start position of the concerned list of data 687 | * A `limit` : the number of items to be retrieved. Note that a default limit MUST be set. 688 | 689 | ```log 690 | GET /customers?offset=5&limit=8 691 | 692 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 693 | ^----------------------^ 694 | offset limit 695 | ``` 696 | 697 | **Response** 698 | 699 | ```json 700 | { 701 | "data": [4, 5, 6, 7, 8, 9, 10, 11], 702 | "count": 8, 703 | "offset" : 5, 704 | "total" : 15 705 | } 706 | ``` 707 | 708 | ### Advantages of offsets 709 | 710 | This type of pagination has several advantages: 711 | * It gives the user the ability to see the total number of pages and their progress through that total 712 | * It gives the user the ability to jump to a specific page within the set 713 | * It’s easy to implement as long as there is an explicit ordering of the results from a query 714 | 715 | ### Drawbacks of offsets 716 | 717 | * Bad for large data sets* - As the `offset` increases the farther you go within the dataset, the database still has to read up to `offset + count` rows from disk (ie. `> 10k rows`) 718 | 719 | * Bad for real-time data* - For mostly static content where items don’t move between pages frequently, offsets pagination is great. But it isn't always the case, specifically because items are sometimes added and removed while the user is navigating to different pages. Here's what can happen when using offsets on dynamic data : 720 | 721 | 1. **Displaying the same item twice**. This can happen if a new item was added at the top of the list, causing the skip and limit approach to show the item at the boundary between pages twice. 722 | 723 | **Example** : let's consider a list of 6 items **at time t**. The user performs a request to fetch the first page (`GET /items?limit=3`). Now let's say a new item was added at the top of the list and the user performs another request to fetch the second page (`GET /items?limit=3&offset=3`). It the state hadn't changed, he would have gotten the second page with items `[4, 5, 6]`, though he will get a response containing items `[3, 4, 5]`, item 3 being a duplicate. 724 | 725 | 726 | 727 | 2. **Skipping an item**. Similarly to the example above, if an item is removed from the list we'll skip an item. 728 | 729 | Though offsets can be used in 90% of the cases, it also means that for certain kinds of APIs, using this technique doesn’t make sense because the set of data and the boundaries between loaded sections is constantly changing (i.e. real time data). **In this case, use cursor based pagination**. 730 | 731 | ## Pagination & Hypermedia 732 | 733 | Pagination can be made easier for the consumer by returning preformatted URIs to fetch the **next** and **previous** pages. All APIs using hypermedia MUST perform pagination using HAL. 734 | 735 | ```log 736 | GET /cars/ HTTP/1.1 737 | ``` 738 | 739 | **Sample list of car objects using HAL** 740 | 741 | *Note : Using offsets pagination (in the case of cursor based pagination, include cursor instead)* 742 | 743 | ```json 744 | { 745 | "_links": { 746 | "self": { 747 | "href": "/cars" 748 | }, 749 | "first": { 750 | "href": "/cars?offset=0" 751 | }, 752 | "next": { 753 | "href": "/cars?offset=10&limit=10" 754 | }, 755 | "prev": { 756 | "href": "/cars?offset=0" 757 | }, 758 | "last": { 759 | "href": "/cars?offset=90&limit=10" 760 | } 761 | }, 762 | "count": 3, 763 | "total": 500, 764 | "_embedded": { 765 | "cars": [ 766 | { 767 | "_links": { 768 | "self": { 769 | "href": "/cars/123" 770 | } 771 | }, 772 | "id": 123, 773 | "owner": "John Doe" 774 | }, 775 | { 776 | "_links": { 777 | "self": { 778 | "href": "/cars/283" 779 | } 780 | }, 781 | "id": 283, 782 | "owner": "Mark Nyse" 783 | }, 784 | ] 785 | } 786 | } 787 | ``` 788 | 789 | 790 | ## Caching 791 | 792 | The ability to cache and reuse previously fetched resources is a critical aspect of optimizing for performance. Every browser comes with an implementation of an HTTP cache. Developers MUST ensure that each server response provides the correct HTTP header directives to instruct the browser on when and for how long the browser can cache the response. 793 | 794 | ### Caching headers 795 | 796 | This table summarizes the most used caching techniques : 797 | 798 | |Header | Definition | 799 | |--|--| 800 | | `Cache-Control : no-store` | **Disallows the browser and all intermediate caches** from storing any version of the returned response. Every time the user requests this asset, a request is sent to the server and a full response is downloaded. This is equivalent to no caching at all. | 801 | | `Cache-Control : private` | Disallows any intermediate cache to cache the response. For instance, a user's browser can cache an HTML page with private user information, but a CDN can't cache the page. | 802 | | `Cache-Control : max-age` | Specifies the maximum time in seconds that the fetched response is allowed to be reused from the time of the request. For instance if `Cache-Control : maxe-age=60` header is set, any call made within 60 seconds will get a cached response. | 803 | | `Last-Modified` | Contains the date and time at which the origin server believes the resource was last modified. It is used as a validator to determine if a resource received or stored is the same. Must be validated against `If-Modified-Since` & `If-Unmodified-Since` headers. | 804 | | `Expires` | Tells the client when the resource is going to expire. Usually has a date value that specifies from when the resource will be considered stale (possibly out-of-date), and so it needs to be re-validated. For instance if `Expires : Wed, 31 Dec 2018 07:28:00 GMT` header is set, any request made to the server before the specified date will return a cached response. | 805 | | `Etag` | The ETag is a unique identifier for your response: it is used on conditional requests using `If-None-Match` header. *Note*: you have to make sure the server provides a validation token (ETag) service| 806 | 807 | ### Caching policies 808 | 809 | API developers and designers MUST define and configure the appropriate per-resource settings, as well as the overall "caching hierarchy." : try to find a balance between good and bad reactivity depending on the resource type. API designers MUST determine the best cache hierarchy for their API : the combination of resource URLs with content fingerprints (Etag) and short or no-cache lifetimes allows you to control how quickly the client picks up updates. 810 | 811 | #### Caching dynamic data 812 | 813 | You cannot cache for long periods of time, such as days, hours or sometimes even minutes because data becomes stale too quickly. That doesn't mean, however, that such data shouldn't be cached at all. When caching resources for short periods of time you should be using HTTP caching instructions that do not rely on shared understanding of time, such as `Cache-Control : max-age`, `Expires` and `ETags` 814 | 815 | > Dynamic data is data that is often changing includes GPS location, battery voltage, tire pressure etc. 816 | 817 | #### Caching near-static data 818 | 819 | If you are caching resources (API responses) for sufficiently long periods of time (hours, days, potentially: months) you usually do not have to worry about the issues related to date-time-based caching. For facilitating caching of near-static data, you could use two approaches: 820 | 821 | - `ETags` that do not rely on shared agreement on time 822 | - `Last-Modified` : header that is date-time-centric 823 | 824 | > Near static data includes country codes, static images like icons, localization labels etc. 825 | 826 | #### No cache 827 | 828 | You can choose not to cache response, in real-time systems for examples, however this comes with great responsibility. The ability to cache and reuse previously fetched resources is a critical aspect of optimizing for performance. Even for dynamic data, caching can tremendously increase performance. 829 | 830 | > Real time data includes car speed, precise GPS location etc. 831 | 832 | ### Caching strategy 833 | 834 | There's no one best cache strategy. API designers and developers MUST take several parameters into account while working on caching strategy : 835 | - **Type of data served** : as we've seen before, dynamic and static data will not have the same caching policy. 836 | - **Traffic patterns** : caching was designed to optimize performances by limiting server calls - if your API is used be a few consumers, caching might not be as critical as if your API was used by millions of people. 837 | - **Application-specific requirements for data freshness** : caching is application specific, meaning that a resource might not be cached the same way across all applications. 838 | *example* : a GPS location might not be cached the ame way in : 839 | - Real-time applications (Waze for instance) : data has ~1sec or less lifetime 840 | - A car dealership application to know approximately where the car is located : data has a ~1min lifetime 841 | 842 | Developers MAY refer to this diagram when deciding on which caching technique to choose : 843 | 844 | 845 | 846 | # Version Management 847 | 848 | This section describes how to version APIs and most specifically what are the invocation rules. 849 | 850 | ## Semantics 851 | 852 | A version is written as follows : 853 | - **major version** : non-retro compatible updates 854 | - **minor version** : retro compatible updates 855 | - **patch version** : mostly bug fixing 856 | 857 | \**Retro compatibility : updates that are still compatible with previous versions of the API* 858 | 859 | ## Versioning Policies 860 | 861 | API’s are versioned products and MUST adhere to the following versioning principles, as per [semantic versionning](https://semver.org/). 862 | 863 | 1. API specifications MUST follow the versioning scheme where where the `v` introduces the version, the major is an ordinal starting with `1` for the first LIVE release, and minor is an ordinal starting with `0` for the first minor release of any major release 864 | 3. API endpoints MUST only reflect the major version 865 | 5. A minor API version MUST maintain backward compatibility with all previous minor versions, within the same major version 866 | 6. A major API version MAY maintain backward compatibility with a previous major version 867 | 868 | ## Version Invocation 869 | 870 | APIs MUST invoke the version in the url of the request. 871 | 872 | ```log 873 | https://api.mpsa.com/manufacturing/factory/v1/customers/456 874 | ``` 875 | 876 | APIs MUST NOT invoke the version number in the header of the request. 877 | 878 | # Asynchronism 879 | 880 | Certain types of operations might require processing of the request in an asynchronous manner in order to avoid long delays on the client side and prevent long-standing open client connections waiting for the operations to complete. Usually, asynchronism should be considered when a delays exceed 400ms. If that is the case, API designers should ask themselves if such delay is problematic or not. 881 | 882 | ## Operation Completion Notification 883 | 884 | There exists multiple ways to notify the API consumer that the operation has finished executing : 885 | * **Webhooks** : force the consumer to implement web hooks to retrieve the operation's response. While this solution is ideal and is RECOMMENDED for all APIs, consumer might not always support it. 886 | * **Polling** : force the consumer to poll until the operation has finished executing 887 | * **External Notifications** : notify the operation completion via external notifications such as email, text message etc. Mostly used in cases where the consumer is a human. 888 | 889 | ## Asynchronism Patterns 890 | 891 | ### Webhooks 892 | 893 | The time it takes for an operation to finish may vary : [polling](#polling) forces consumers to figure out how often to make the polling calls which is far from being optimal. Instead, it is RECOMMENDED that APIs use webhooks whenever possible. 894 | 895 | Webhooks solve this problem by allowing a web service to provide other services with near real-time information using HTTP POST requests. In short : instead of asking the server if it has data, the consumer will be notified to a given URI that the data is available. 896 | 897 | 898 | 899 | **What API conceptors need to provide :** 900 | 901 | * Documentation the way consumers can specify the URI the webhook will serve 902 | * Provide information regarding the webhooks' payload : a webhook MUST at least provide the information in the table below : 903 | 904 | | Attribute | Type | Description | 905 | |---------------|---------------|------------------------------------| 906 | | `id` | `string` | Unique identifier for the webhook. | 907 | | `created` | `timestamp` | Unique identifier for the webhook. | 908 | | `data` | `url` | URL to retrieve data associated with the event. | 909 | | `type` | `string` | Description of the event (e.g: `car.registered` or `user.created`) | 910 | 911 | **Sample webhook payload** 912 | 913 | ```json 914 | { 915 | "id": "evt_1BqTZj2eZvKYlo2CvwY0ZQBr", 916 | "created": 1517435823, 917 | "data": "https://api.mpsa.com/manufacturing/factory/v1/customers/123123", 918 | "type": "user.created" 919 | } 920 | ``` 921 | 922 | **What API consumers must implement :** 923 | 924 | Consumer MUST setup an API endpoint to receive webhook's payloads and returing appropriate status codes. In pseudo code : 925 | 926 | ```log 927 | post "/my/webhook/url" do 928 | # Retrieve the request's body and parse it as JSON 929 | event_json = JSON.parse(request.body.read) 930 | 931 | # Do something with event_json 932 | 933 | status 200 934 | end 935 | ``` 936 | 937 | ### Polling 938 | 939 | 940 | 941 | In use cases where webhooks cannot be used, APIs MUST employ the following pattern : 942 | 943 | **For `POST` requests :** 944 | 945 | * Return the `202 Accepted` HTTP response code. 946 | * In the response body, include one or more URIs as hypermedia links, which could include: 947 | * The final URI of the resource where it will be available in future if the ID and path are already known. Clients can then make an HTTP `GET` request to that URI in order to obtain the completed resource. Until the resource is ready, the final URI SHOULD return the HTTP status code `404 Not Found`. This is equivalent to polling. 948 | 949 | `{ "rel": "self", "href": "/v1/namespace/resources/{resource_id}", "method": "GET" }` 950 | 951 | * A temporary request queue URI where the status of the operation may be obtained via some temporary identifier. Clients SHOULD make an HTTP `GET` request to obtain the status of the operation which MAY include such information as completion state, ETA, and final URI once it is completed. This is equivalent to polling. 952 | 953 | `{ "rel": "self", "href": "/v1/queue/requests/{request_id}, "method": "GET" }"` 954 | 955 | 956 | **For `PUT`/`PATCH`/`DELETE`/`GET` requests:** 957 | 958 | Like `POST`, you can support `PUT`/`PATCH`/`DELETE`/`GET` to be asynchronous. The behaviour would be as follows: 959 | 960 | * Return the `202 Accepted` HTTP response code. 961 | * In the response body, include one or more URIs as hypermedia links, which could include: 962 | * A temporary request queue URI where the status of the operation may be obtained via some temporary identifier. Clients SHOULD make an HTTP `GET` request to obtain the status of the operation which MAY include such information as completion state, ETA, and final URI once it is completed. 963 | 964 | `{ "rel": "self", "href": "/v1/queue/requests/{request_id}, "method": "GET" }"` 965 | 966 | **APIs that support both synchronous and asynchronous processing for an URI:** 967 | 968 | APIs that support both synchronous and asynchronous operations for a particular URI and an HTTP method combination, MUST recognize the `Prefer` header and exhibit following behavior: 969 | 970 | * If the request contains a `Prefer=respond-async` header, the service MUST switch the processing to asynchronous mode. 971 | * If the request doesn't contain a `Prefer=respond-async` header, the service MUST process the request synchronously. 972 | 973 | It is desirable that all APIs that implement asynchronous processing, also support [webhooks](https://en.wikipedia.org/wiki/Webhook) as a mechanism of pushing the processing status to the client. 974 | 975 | 976 | ### External Notifications 977 | 978 | API consumers can be notified via external notfications such as an email, sms etc. This technique is rarely used and can be applied only to very specific use cases. 979 | --------------------------------------------------------------------------------