🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practices and Guidelines
1. API and RAML Design Best Practices and
Guidelines
[Surat] MuleSoft Meetup Group
[24th July 2021]
11:00 IST (GMT+05:30)
2. 2
Organizers
Jitendra Bafna
About the organizer:
⮚ MuleSoft Ambassador
⮚ Surat and Nashik MuleSoft Meetup Leader.
⮚ 12.5+ Years of Experience in Integrations and API Technologies.
⮚ Certified MuleSoft Integration Architect and platform Architect.
3. 3
Organizers
Nitish Jain
Consultant
IBM
About the organizer :
⮚ Working as Consultant at IBM.
⮚ Surat MuleSoft Meetup Leader.
⮚ 2.5+ Years of Experience in Integrations and API Technologies.
⮚ Certified MuleSoft Developer and Platform Architect.
4. Certifications
• MuleSoft Certified Developer
• MuleSoft Certified Integration Architect
Tirthankar Kundu
Lead Software Engineer
Persistent Systems
Speakers
About the speaker:
⮚ 3+ years of experience in Insurance Domain
⮚ Cloud and Integration
⮚ Proficient in Frontend and Backend Technologies
⮚ Second Runner Up at MuleSoft Hackathon 2020
⮚ Works on – Java, .NET, Android, Angular and of course MuleSoft !
5. 5
● REST API Design Best Practices
● RAML Design Best Practices
● Trivia Quiz
● Networking
● Wrap-up
Agenda
7. What is API ?
● An API is a set of definitions and protocols for building and integrating application software.
● It’s sometimes referred to as a contract between an information provider and an information
user.
● If you want to interact with a computer or system to retrieve information or perform a function,
an API helps you communicate what you want to that system so it can understand and fulfill the
request
8. API Characteristics
● Easy to learn
● Easy to use, even without documentation
● Hard to misuse
● Easy to read and maintain code that uses it
● Sufficiently powerful to satisfy requirements
● Easy to extend
● Appropriate to audience
9. HTTP Verbs and Methods
Below is a list of methods RESTful HTTP APIs / services SHOULD support. Not all resources will support all
methods, but all resources using one or more of the methods below MUST conform to their usage.
Method Description Is Idempotent?
GET Return the current value of an object. True
PUT Update an object or create an object whenever applicable. True
DELETE Delete an object. True
POST Create a new object based on data provided. False
HEAD Return metadata of an object for a GET response. Resources which
support the GET method MAY support the HEAD method as well.
True
PATCH Apply a partial update to an object. False
OPTIONS Get information about a request; see below for details. True
10. API Principle – 1 (Use Nouns in URI, not verbs)
REST API’s should be designed for resources, which can be entities or services, etc., therefore they must
always be nouns and use HTTP verbs for operations.
For example, use POST /employees instead of /createEmployees.
● GET https://dev.api.example.com/api/v1.0/invoices (Get All Invoices)
● POST https://dev.api.example.com/api/v1.0/invoices (Create Invoices)
● GET https://dev.api.example.com/api/v1.0/invoices/{invoiceId} (Get Single Invoices)
● DELETE https://dev.api.example.com/api/v1.0/invoices/{invoiceId} (Delete Invoices)
11. API Principle – 2 (Use Plural Noun)
Generally, we prefer to use plurals but there is no hard rule that one can’t use singular for resource name.
The ideology behind using plurals is that we are operating on one resource from collection of resources so to
depict collection we use plural.
● GET https://dev.api.example.com/api/v1.0/orders (Get All Orders)
● POST https://dev.api.example.com/api/v1.0/orders (Create Orders)
● GET https://dev.api.example.com/api/v1.0/orders/{orderId} (Get Single Order)
● DELETE https://dev.api.example.com/api/v1.0orders/{orderId} (Delete Order)
12. API Principle – 3 (Let HTTP Verbs Defined action)
API’s should only provide nouns for resources and let the HTTP verbs (GET, POST, PUT, DELETE) define the
action to be performed on a resource.
Resource GET (Read) POST (Create) PUT (Update) DELETE (Delete)
/v1.0/invoices Returns a list of
invoice
Creates a new
Invoice
Bulk updates of
invoices
Delete all invoices
/v1.0/invoices/IN
V123
Returns a specific
invoice
Method not
allowed (405)
Updates a specific
invoice
Deletes a specific
invoice
13. API Principle – 4 (GET Method and Query
Parameter Should Not Alter State)
API’s should only provide nouns for resources and let the HTTP verbs (GET, POST, PUT, DELETE) define the
action to be performed on a resource.
Use POST, DELETE or PUT instead of GET to alter the state. Do Not use GET to alter the changes.
Incorrect Way
● GET https://dev.api.example.com/api/v1.0/orders/v1.0/activate
● GET https://dev.api.example.com/api/v1.0/orders?activate
Correct Way
● POST https://dev.api.example.com/api/v1.0/orders/activate
14. API Principle – 5 (Provide filtering, sorting, field
selection and paging for collections)
Filtering:
Use query parameters defined in the URL for filtering a resource from the server. For example, if we would
like to fetch all invoices for particular company
GET https://dev.api.example.com/api/v1.0/invoices?companyName=xyz
In the example above, companyName is the filter parameter.
Searching:
To get the results with powerful search queries instead of basic filters, one could use multiple parameters in
a URI to request to fetch a resource from the server.
GET https://dev.api.example.com/api/v1.0/invoices?companyName=xyz&status=active
15. ● Use HTTP Verbs the right way
○ REST API encourages us to use an HTTP method for each of the application’s CRUD actions. Few of the HTTP
Verbs available are: GET, POST, PUT, DELETE, and PATCH
● Use proper status codes
○ One of the most important features of a REST API is that the status codes returned are related.
○ For example, a status 200, immediately gives a notion of success while 400 or 500 gives an idea of failure.
● Add filter, pagination and sort capability
○ Helps expanding the functionalities of our API
○ Reduce the consumption of resources on our server
API Principle – 6 (API Documentation)
16. Versioning APIs always helps to ensure backward compatibility of a service while adding new features or updating
existing functionality for new clients. One of the most effective ways of versioning is URI based versioning. URI based
versioning is transparent to clients as clients can see version number in API and client is always aware that there can
be new versions of API.
When to Version
○ APIs only need to be up-versioned when a breaking change is made. Breaking changes include:
● a change in the format of the response data for one or more calls
● a change in the response type (i.e. changing an integer to a float)
● removing any part of the API.
Breaking changes should always result in a change to the major version number for an API or content response type.
Non-breaking changes, such as adding new endpoints or new response parameters, do not require a change to the
major version number. However, it can be helpful to track the minor versions of APIs when changes are made to
support customers who may be receiving cached versions of data or may be experiencing other API issues.
API Principle – 7 (Version Your API)
17. Use correct HTTP status code to provide responses to clients. It can be a success or failure response, but it should
define what the respective success or failure means from a server perspective.
2XX – Success
3xx – Redirection
API Principle – 8 (HTTP Status Code)
200 OK Returned by a successful GET or DELETE operation. PUT or POST can also use
this, if the service does not want to return a resource back to the client after
creation or modification.
201 Created Response for a successful resource creation by a POST request.
301 Resource Moved
Permanently
This and all future requests should be directed to the given URI
302 Resource Moved
Temporarily
A web server sends “301 – Moved Permanently” status code when there is a
permanent redirect set to an original URL to forward the user agent to another
URL.
304 Not Modified Used if HTTP caching header is implemented.
18. 4XX – Client Error
5XX – Server Error
These errors occur due to server failures or issues with the underlying infrastructure.
API Principle – 8 (HTTP Status Code)
400 Bad Request When an HTTP request body can’t be parsed. For example, if an API is expecting a
body in a JSON format for a POST request, but the body of the request is
malformed.
401 Unauthorized Authentication is unsuccessful (or credentials have not been provided) while
accessing the API.
403 Forbidden If a user is not Authorized to perform an action although authentication
information is correct.
405 Method Not Allowed If the user is trying to violate an API contract, for example, trying to update a
resource by using a POST method.
19. ● Caching is one of the most effective methods for improving an API's speed and resource use.
● Caching static data wouldn't be a problem but for data which is dynamic we might have to be a bit more careful.
API Principle – 9 (Caching)
20. If a resource is related to another resource use sub resources. Let's consider the use case invoice can have invoice
lines and order can have order Items. In such a case invoice will be the parent resource and invoice line is sub
resources.
API Principle – 10 (Use sub resources for relation)
Use Case Method Url
Fetch Invoice Lines for
particular invoice
GET https://dev.api.example.com/v1.0/invoices/{invoiceId}/lines
Fetch Single Invoice Line GET https://dev.api.example.com/v1.0/invoices/{invoiceId}/lines/{lineN
umber}
Create Invoice Line POST https://dev.api.example.com/v1.0/invoices/{invoiceId}/lines
21. API URI’s
The structure of a URI is central to how APIs are organized and categorized within your enterprise domain. A good
URI taxonomy helps to categories your APIs across functional domains, regions, and relationships (hierarchical)
between them. A good URI also helps to govern the lifecycle of your API through versioning practices.
The recommended URI Structure is shown below:
● https://dev.api.example.com/api/v1.0/invoices
● https://dev.api.example.com/api/v1.0/orders/{orderId}
● https://dev.api.example.com/api/v1.0/invoices?companyName=xyz
API URI’s
22. API URI’s
Part Description Example
${domain} The domain of the enterprise api.dev.example.com
${appName} name of application logger
${version} The version of the API. Depending on requirements, the
version can reflect only major versions or include a more
hierarchical convention to identify minor versions
v1.0, v2.0
${resources} The name of the resource that represents the actual
object. An API may contain one or more resources. The
resource can also be referred to as the API endpoint
invoices
${resource-id} The id of the resource to be fetched/updated. The
resource id is optional and it is not applicable when we do
a POST
12345
${sub-resources} The name of the resource that represents the sub object. invoiceLines
${sub-resource-id} The id of the sub resource to be fetched/updated. 211232
${queryParams} Query parameters/strings are often used to carry
identifying information in the form of "key=value" pairs
companyName=xyz
24. What is RAML ?
RAML is an API design language that allows developers to take advantage of the full API Design Lifecycle,
meaning that they can visually design their APIs, test them, and get user feedback without ever having to write
a single line of code.
RAML describes APIs in a human readable format - plain text.
25. RAML Files
RAML file names are in lowercase, alphanumeric characters using kebab-case (i.e. hyphen-separated).
For example:
• acme-banking-api.xml
• account-example.raml
• acme-bank-doc.raml
26. RAML Header
API Titles
The title of the API should be a short, plain-text label for the API.
title: ACME Banking API
Version
Each API should have a corresponding alphanumeric version
number.
version: 1.0.0
Protocols
The optional protocols node specifies the protocols that an API supports. If the protocols
node is not explicitly specified, the protocol in the baseUri node is used.
protocols: [HTTP, HTTPS]
27. RAML Media Type
Specifying the OPTIONAL mediaType node sets the default media type for responses and requests that have a
body.
NOTE: If mediaType is set at the root level, the media type within each body definition does not need to be
specified.
mediaType: application/json
28. RAML Data Types
● RAML DataTypes provide a concise and powerful way of describing the information utilized within the
API. Data types add rules for validating data against a type declaration. DataTypes should be created as
separate files and included at the start of the API RAML file.
For example (account.raml):
#%RAML 1.0 DataType
type: object
properties:
accountID: string
accountType:
enum: [Checking, Savings, Overdraft Savings, Credit Card]
accountNumber: string
accountOwner:
type: array
items: !include account-owner.raml
accountBalance: !include money.raml
IBAN:
type: string
pattern: ^[A-Z]{2,2}[0-9]{2,2}[a-zA-Z0-9]{1,30}$
bank: !include bank.raml
interestRate?:
type: number
format: double
createdAt: datetime
modifiedAt?: datetime
types:
customer: !include datatypes/customer.raml
account: !include datatypes/account.raml
transaction: !include datatypes/transaction.raml
The types node within the API RAML is used to refer to external
DataTypes:
29. RAML Resource Types
ResourceTypes are a powerful way to reuse patterns across multiple resources and methods. The patterns
provided by ResourceTypes encourages consistency and reduces complexity for API designers and consumers.
Usage of ResourceTypes is optional but is highly encouraged since it simplifies the API design and improves
readability. ResourceTypes should be created as separate files and included at the start of the API RAML file.
For example (collection.raml):
#%RAML 1.0 ResourceType
post?:
description: Add a new <<resourcePathName | !singularize>>
displayName: Add new <<resourcePathName | !singularize>>
body:
type: <<resourcePathName | !singularize | !uppercamelcase>>
responses:
201:
headers:
Location:
description: URL of the new <<resourcePathName | !singularize>> information
example: /<<resourcePathName>>/8f19cb50-3f57-4d38
body:
202:
description: The request has been accepted for processing. Use the URI provided in the Location header of the response to monitor the status.
headers:
Location:
example: /<<resourcePathName>>/1234/status
503:
body:
type: <<customErrorDataType>>
The resourceTypes node within the API
RAML is used to refer to external
ResourceTypes:
resourceTypes:
collection: !include resourceTypes/collection.raml
member: !include resourceTypes/member.raml
Resource types can be mapped in the
API RAML by referencing the assigned
type:
/customers:
type:
collection:
customErrorDataType: customErrorMessage
30. RAML Traits
A Trait, like a method, can provide method-level nodes such as description, headers, query string parameters,
and responses. Methods that use one or more traits inherit nodes of those traits.
Usage of Traits, like ResourceTypes, is optional but is highly encouraged since it simplifies the API design and
improves readability. Traits should be created as separate files and included at the start of the API RAML file.
For example (cacheable.raml):
#%RAML 1.0 Trait
usage: Apply this trait to any GET method that supports caching control.
responses:
200:
headers:
Cache-Control:
description: |
Activates caching and defines cache behavior through cache response directives.
Usually defines public or private (cacheable by proxy or not) and max-age for resource.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more information.
example: private, max-age=31536000
Expires:
description: |
Sets a date in RFC 1123 format from which the cached resource should no longer be considered valid.
If both the Expires header and max-age in the Cache-Control header are set, max-age will take
precedence.
type: datetime
example: Tue, 18 Apr 2017 09:30:41 GMT
format: rfc2616
The traits node within the API RAML is used
to refer to external Traits:
traits:
cacheable: !include traits/cacheable.raml
Traits can be mapped in the API RAML by
referencing the assigned trait:
/customers:
get:
is: [ cacheable ]
description: Retrieve a list of customers
displayName: Get all customers
securedBy: oauth2_0
31. RAML Security Schemes
Each authentication pattern supported by the API must be expressed as an element of the securitySchemes
node value. The security schemes should be created under a separate folder and included within the API RAML
file.
For example (oauth2.raml):
#%RAML 1.0 SecurityScheme
type: OAuth 2.0
description: Apply the OAuth 2.0 security policy to resource methods for authenticating API requests
describedBy:
headers:
Authorization:
description: |
Used to send a valid OAuth2 access token. Do not use with the "access_token" query. string parameter.
type: string
queryParameters:
access_token:
description: |
Used to send a valid OAuth2 access token. Do not use together with the "Authorization" header.
type: string
responses:
401:
description: |
Bad or expired token. This can happen if the API consumer uses a revoked or expired access token. To fix, you should re-
authenticate the user.
403:
description: |
Bad OAuth request (wrong consumer key, bad nonce, expired timestamp...). Unfortunately, re-authenticating the user won't
help here.
settings:
authorizationUri: https://placeholder.com/oauth2/authorize
accessTokenUri: https://placeholder.com/oauth2/access_token
authorizationGrants: implicit
The securitySchemes node within the API
RAML is used to refer to external security
schemes:
securitySchemes:
oauth2_0: !include securitySchemes/oauth2.raml
32. Structuring RAML Resources
A RAML file may reference additional resources, like traits and resourceTypes, JSON Schemas, or example data.
API authors are encouraged to follow certain conventions for structuring and naming external resources.
According to these conventions, the following relative URL paths and file suffixes should be used:
Resource Path Suffix Example
API Definition / .raml acme-banking.raml
Trait /traits/ .raml cacheable.raml
Resource Types /resourceTypes/ .raml collection.raml
Security Schemes /securitySchemes/ .raml oauth2.raml
Data Types /dataTypes/ .raml account.raml
.schema.json account.schema.json
.xsd account.xsd
Documentation /documentation/ .raml acme-bank-doc.xml
Examples /examples/ .raml account-example.raml
.json account-example.json
.xml account-example.xml
33. Error Messages
Every API should use a common error message schema for when an error
needs to be returned in a response payload:
The common error type schema contains these attributes:
name – Name of the API returning the response.
code – The HTTP Status code of the response.
title – The human-readable text of the equivalent HTTP status code.
link – URL that provides additional information on the status code
(optional).
transactionID – The unique ID associated with the transaction in
which this API is involved (also known as a correlation ID).
description – A detailed message describing the problem in relation to
the error type in human-readable form.
invocationTimestamp – The time at which the API was invoked
(optional).
{
"name": "Reporting Process API",
"code": "201",
"title": "Created",
"link": "http://mulesoft.org/..../LoB/API.html#201",
"transactionID": "c70332d0-260f-11e7-98a1-
c4b301c8ce30",
"description": "Report Generated Successfully.",
"invocationTimestamp": "2017-10-02T17:42:38Z"
}