SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
API and RAML Design Best Practices and
Guidelines
[Surat] MuleSoft Meetup Group
[24th July 2021]
11:00 IST (GMT+05:30)
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
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.
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
● REST API Design Best Practices
● RAML Design Best Practices
● Trivia Quiz
● Networking
● Wrap-up
Agenda
REST API Best Practices
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
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
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
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)
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)
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
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
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
● 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)
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)
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.
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.
● 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)
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
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
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
RAML Best Practices
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.
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
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]
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
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:
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
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
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
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
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"
}
Thank You

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

OpenShift 4, the smarter Kubernetes platform
OpenShift 4, the smarter Kubernetes platformOpenShift 4, the smarter Kubernetes platform
OpenShift 4, the smarter Kubernetes platform
 
Introduction to Helm
Introduction to HelmIntroduction to Helm
Introduction to Helm
 
Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...
Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...
Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Containers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatContainers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red Hat
 
Washington DC MuleSoft Meetup: CI/CD Pipeline with MuleSoft and Azure DevOps
Washington DC MuleSoft Meetup: CI/CD Pipeline with MuleSoft and Azure DevOpsWashington DC MuleSoft Meetup: CI/CD Pipeline with MuleSoft and Azure DevOps
Washington DC MuleSoft Meetup: CI/CD Pipeline with MuleSoft and Azure DevOps
 
Intro to GitOps & Flux.pdf
Intro to GitOps & Flux.pdfIntro to GitOps & Flux.pdf
Intro to GitOps & Flux.pdf
 
VPCs, Metrics Framework, Back pressure : MuleSoft Virtual Muleys Meetups
VPCs, Metrics Framework, Back pressure  : MuleSoft Virtual Muleys MeetupsVPCs, Metrics Framework, Back pressure  : MuleSoft Virtual Muleys Meetups
VPCs, Metrics Framework, Back pressure : MuleSoft Virtual Muleys Meetups
 
Gitlab, GitOps & ArgoCD
Gitlab, GitOps & ArgoCDGitlab, GitOps & ArgoCD
Gitlab, GitOps & ArgoCD
 
Docker and Kubernetes 101 workshop
Docker and Kubernetes 101 workshopDocker and Kubernetes 101 workshop
Docker and Kubernetes 101 workshop
 
Openshift Container Platform
Openshift Container PlatformOpenshift Container Platform
Openshift Container Platform
 
Microservices on Anypoint Platform
Microservices on Anypoint PlatformMicroservices on Anypoint Platform
Microservices on Anypoint Platform
 
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...
 
Monitoring Kubernetes with Prometheus
Monitoring Kubernetes with PrometheusMonitoring Kubernetes with Prometheus
Monitoring Kubernetes with Prometheus
 
Mule Runtime: Performance Tuning
Mule Runtime: Performance Tuning Mule Runtime: Performance Tuning
Mule Runtime: Performance Tuning
 
Red Hat OpenShift Container Platform Overview
Red Hat OpenShift Container Platform OverviewRed Hat OpenShift Container Platform Overview
Red Hat OpenShift Container Platform Overview
 
Cloudhub 2.0
Cloudhub 2.0Cloudhub 2.0
Cloudhub 2.0
 
Introduction to GitHub Actions
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub Actions
 
MuleSoft Sizing Guidelines - VirtualMuleys
MuleSoft Sizing Guidelines - VirtualMuleysMuleSoft Sizing Guidelines - VirtualMuleys
MuleSoft Sizing Guidelines - VirtualMuleys
 
Rancher 2.0 Technical Deep Dive
Rancher 2.0 Technical Deep DiveRancher 2.0 Technical Deep Dive
Rancher 2.0 Technical Deep Dive
 

Similar a MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practices and Guidelines

Similar a MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practices and Guidelines (20)

REST API Basics
REST API BasicsREST API Basics
REST API Basics
 
A Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API TestingA Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API Testing
 
Cqrs api
Cqrs apiCqrs api
Cqrs api
 
JOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best Practices
 
Api design and development
Api design and developmentApi design and development
Api design and development
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
Best Practices in Api Design
Best Practices in Api DesignBest Practices in Api Design
Best Practices in Api Design
 
Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest api
 
Crafting APIs
Crafting APIsCrafting APIs
Crafting APIs
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
APITalkMeetupSharable
APITalkMeetupSharableAPITalkMeetupSharable
APITalkMeetupSharable
 
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
 
Hia 1691-using iib-to_support_api_economy
Hia 1691-using iib-to_support_api_economyHia 1691-using iib-to_support_api_economy
Hia 1691-using iib-to_support_api_economy
 
EBSCoupaIntegration
EBSCoupaIntegrationEBSCoupaIntegration
EBSCoupaIntegration
 
Best practices and advantages of REST APIs
Best practices and advantages of REST APIsBest practices and advantages of REST APIs
Best practices and advantages of REST APIs
 
Web API with ASP.NET MVC by Software development company in india
Web API with ASP.NET  MVC  by Software development company in indiaWeb API with ASP.NET  MVC  by Software development company in india
Web API with ASP.NET MVC by Software development company in india
 
POSTMAN.pptx
POSTMAN.pptxPOSTMAN.pptx
POSTMAN.pptx
 
Lunacloud's Compute RESTful API - Programmer's Guide
Lunacloud's Compute RESTful API - Programmer's GuideLunacloud's Compute RESTful API - Programmer's Guide
Lunacloud's Compute RESTful API - Programmer's Guide
 

Más de Jitendra Bafna

Más de Jitendra Bafna (20)

MuleSoft Surat Meetup#55 - Unleash the power of Anypoint MQ
MuleSoft Surat Meetup#55 - Unleash the power of Anypoint MQMuleSoft Surat Meetup#55 - Unleash the power of Anypoint MQ
MuleSoft Surat Meetup#55 - Unleash the power of Anypoint MQ
 
MuleSoft Surat Meetup#54 - MuleSoft Automation
MuleSoft Surat Meetup#54 - MuleSoft AutomationMuleSoft Surat Meetup#54 - MuleSoft Automation
MuleSoft Surat Meetup#54 - MuleSoft Automation
 
MuleSoft Surat Meetup#53 - MuleSoft for Clinical Trial Modernization
MuleSoft Surat Meetup#53 - MuleSoft for Clinical Trial ModernizationMuleSoft Surat Meetup#53 - MuleSoft for Clinical Trial Modernization
MuleSoft Surat Meetup#53 - MuleSoft for Clinical Trial Modernization
 
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...
 
MuleSoft Surat Meetup#51 - API Monitoring - Through a New Lens
MuleSoft Surat Meetup#51 - API Monitoring - Through a New LensMuleSoft Surat Meetup#51 - API Monitoring - Through a New Lens
MuleSoft Surat Meetup#51 - API Monitoring - Through a New Lens
 
Engineering Student MuleSoft Meetup#7 - Leveraging MuleSoft Service in Salesf...
Engineering Student MuleSoft Meetup#7 - Leveraging MuleSoft Service in Salesf...Engineering Student MuleSoft Meetup#7 - Leveraging MuleSoft Service in Salesf...
Engineering Student MuleSoft Meetup#7 - Leveraging MuleSoft Service in Salesf...
 
MuleSoft Nashik Meetup#7 - Building FHIR applications in MongoDB using MuleSoft
MuleSoft Nashik Meetup#7 - Building FHIR applications in MongoDB using MuleSoftMuleSoft Nashik Meetup#7 - Building FHIR applications in MongoDB using MuleSoft
MuleSoft Nashik Meetup#7 - Building FHIR applications in MongoDB using MuleSoft
 
MuleSoft Surat Meetup#50 - Ask the MuleSoft Ambassadors + CloudHub 2.0 Overvi...
MuleSoft Surat Meetup#50 - Ask the MuleSoft Ambassadors + CloudHub 2.0 Overvi...MuleSoft Surat Meetup#50 - Ask the MuleSoft Ambassadors + CloudHub 2.0 Overvi...
MuleSoft Surat Meetup#50 - Ask the MuleSoft Ambassadors + CloudHub 2.0 Overvi...
 
MuleSoft Surat Meetup#49 - Robotic Process Automation - Why, Where, When and ...
MuleSoft Surat Meetup#49 - Robotic Process Automation - Why, Where, When and ...MuleSoft Surat Meetup#49 - Robotic Process Automation - Why, Where, When and ...
MuleSoft Surat Meetup#49 - Robotic Process Automation - Why, Where, When and ...
 
MuleSoft Surat Meetup#48 - Anypoint API Governance (RAML, OAS and Async API) ...
MuleSoft Surat Meetup#48 - Anypoint API Governance (RAML, OAS and Async API) ...MuleSoft Surat Meetup#48 - Anypoint API Governance (RAML, OAS and Async API) ...
MuleSoft Surat Meetup#48 - Anypoint API Governance (RAML, OAS and Async API) ...
 
MuleSoft Surat Meetup#47 - Error Handling With MuleSoft
MuleSoft Surat Meetup#47 - Error Handling With MuleSoftMuleSoft Surat Meetup#47 - Error Handling With MuleSoft
MuleSoft Surat Meetup#47 - Error Handling With MuleSoft
 
MuleSoft Surat Meetup#46 - Deep Dive into MUnit With MuleSoft
MuleSoft Surat Meetup#46 - Deep Dive into MUnit With MuleSoftMuleSoft Surat Meetup#46 - Deep Dive into MUnit With MuleSoft
MuleSoft Surat Meetup#46 - Deep Dive into MUnit With MuleSoft
 
MuleSoft Surat Meetup#45 - Anypoint Flex Gateway as a Kubernetes Ingress Cont...
MuleSoft Surat Meetup#45 - Anypoint Flex Gateway as a Kubernetes Ingress Cont...MuleSoft Surat Meetup#45 - Anypoint Flex Gateway as a Kubernetes Ingress Cont...
MuleSoft Surat Meetup#45 - Anypoint Flex Gateway as a Kubernetes Ingress Cont...
 
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With Rust
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With RustMuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With Rust
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With Rust
 
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
 
MuleSoft Nashik Meetup#5 - JSON Logger and Externalize Logs
MuleSoft Nashik Meetup#5 - JSON Logger and Externalize LogsMuleSoft Nashik Meetup#5 - JSON Logger and Externalize Logs
MuleSoft Nashik Meetup#5 - JSON Logger and Externalize Logs
 
MuleSoft Surat Meetup#43 - Combine Service Mesh With Anypoint API Management ...
MuleSoft Surat Meetup#43 - Combine Service Mesh With Anypoint API Management ...MuleSoft Surat Meetup#43 - Combine Service Mesh With Anypoint API Management ...
MuleSoft Surat Meetup#43 - Combine Service Mesh With Anypoint API Management ...
 
Engineering Student MuleSoft Meetup#5 - Error Handling With MuleSoft
Engineering Student MuleSoft Meetup#5 - Error Handling With MuleSoftEngineering Student MuleSoft Meetup#5 - Error Handling With MuleSoft
Engineering Student MuleSoft Meetup#5 - Error Handling With MuleSoft
 
MuleSoft Surat Meetup#42 - Runtime Fabric Manager on Self Managed Kubernetes ...
MuleSoft Surat Meetup#42 - Runtime Fabric Manager on Self Managed Kubernetes ...MuleSoft Surat Meetup#42 - Runtime Fabric Manager on Self Managed Kubernetes ...
MuleSoft Surat Meetup#42 - Runtime Fabric Manager on Self Managed Kubernetes ...
 
MuleSoft Surat Meetup#40 - Watermarking Concept and Fragments in MuleSoft
MuleSoft Surat Meetup#40 - Watermarking Concept and Fragments in MuleSoftMuleSoft Surat Meetup#40 - Watermarking Concept and Fragments in MuleSoft
MuleSoft Surat Meetup#40 - Watermarking Concept and Fragments in MuleSoft
 

Último

💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
Apsara Of India
 
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
mountabuangels4u
 
sample sample sample sample sample sample
sample sample sample sample sample samplesample sample sample sample sample sample
sample sample sample sample sample sample
Casey Keith
 
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
Apsara Of India
 

Último (20)

Ooty Call Girls 8250077686 Service Offer VIP Hot Model
Ooty Call Girls 8250077686 Service Offer VIP Hot ModelOoty Call Girls 8250077686 Service Offer VIP Hot Model
Ooty Call Girls 8250077686 Service Offer VIP Hot Model
 
Ooty call girls 📞 8617697112 At Low Cost Cash Payment Booking
Ooty call girls 📞 8617697112 At Low Cost Cash Payment BookingOoty call girls 📞 8617697112 At Low Cost Cash Payment Booking
Ooty call girls 📞 8617697112 At Low Cost Cash Payment Booking
 
Mathura Call Girls 8250077686 Service Offer VIP Hot Model
Mathura Call Girls 8250077686 Service Offer VIP Hot ModelMathura Call Girls 8250077686 Service Offer VIP Hot Model
Mathura Call Girls 8250077686 Service Offer VIP Hot Model
 
Andheri Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Andheri Call Girls 🥰 8617370543 Service Offer VIP Hot ModelAndheri Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Andheri Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Top travel agency in panchkula - Best travel agents in panchkula
Top  travel agency in panchkula - Best travel agents in panchkulaTop  travel agency in panchkula - Best travel agents in panchkula
Top travel agency in panchkula - Best travel agents in panchkula
 
Hire 💕 8617697112 Reckong Peo Call Girls Service Call Girls Agency
Hire 💕 8617697112 Reckong Peo Call Girls Service Call Girls AgencyHire 💕 8617697112 Reckong Peo Call Girls Service Call Girls Agency
Hire 💕 8617697112 Reckong Peo Call Girls Service Call Girls Agency
 
Siliguri Call Girls 8250077686 Service Offer VIP Hot Model
Siliguri Call Girls 8250077686 Service Offer VIP Hot ModelSiliguri Call Girls 8250077686 Service Offer VIP Hot Model
Siliguri Call Girls 8250077686 Service Offer VIP Hot Model
 
Kolkata Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
Kolkata Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service AvailableKolkata Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
Kolkata Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
 
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
 
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
 
sample sample sample sample sample sample
sample sample sample sample sample samplesample sample sample sample sample sample
sample sample sample sample sample sample
 
Genuine 8250077686 Hot and Beautiful 💕 Chennai Escorts call Girls
Genuine 8250077686 Hot and Beautiful 💕 Chennai Escorts call GirlsGenuine 8250077686 Hot and Beautiful 💕 Chennai Escorts call Girls
Genuine 8250077686 Hot and Beautiful 💕 Chennai Escorts call Girls
 
Call Girls Jaisalmer Just Call 8617370543 Top Class Call Girl Service Available
Call Girls Jaisalmer Just Call 8617370543 Top Class Call Girl Service AvailableCall Girls Jaisalmer Just Call 8617370543 Top Class Call Girl Service Available
Call Girls Jaisalmer Just Call 8617370543 Top Class Call Girl Service Available
 
Night 7k to 12k Daman Call Girls 👉👉 8617697112⭐⭐ 100% Genuine Escort Service ...
Night 7k to 12k Daman Call Girls 👉👉 8617697112⭐⭐ 100% Genuine Escort Service ...Night 7k to 12k Daman Call Girls 👉👉 8617697112⭐⭐ 100% Genuine Escort Service ...
Night 7k to 12k Daman Call Girls 👉👉 8617697112⭐⭐ 100% Genuine Escort Service ...
 
❤Personal Contact Number Mcleodganj Call Girls 8617697112💦✅.
❤Personal Contact Number Mcleodganj Call Girls 8617697112💦✅.❤Personal Contact Number Mcleodganj Call Girls 8617697112💦✅.
❤Personal Contact Number Mcleodganj Call Girls 8617697112💦✅.
 
❤Personal Contact Number Varanasi Call Girls 8617697112💦✅.
❤Personal Contact Number Varanasi Call Girls 8617697112💦✅.❤Personal Contact Number Varanasi Call Girls 8617697112💦✅.
❤Personal Contact Number Varanasi Call Girls 8617697112💦✅.
 
Hire 💕 8617697112 Champawat Call Girls Service Call Girls Agency
Hire 💕 8617697112 Champawat Call Girls Service Call Girls AgencyHire 💕 8617697112 Champawat Call Girls Service Call Girls Agency
Hire 💕 8617697112 Champawat Call Girls Service Call Girls Agency
 
Genuine 8250077686 Hot and Beautiful 💕 Hosur Escorts call Girls
Genuine 8250077686 Hot and Beautiful 💕 Hosur Escorts call GirlsGenuine 8250077686 Hot and Beautiful 💕 Hosur Escorts call Girls
Genuine 8250077686 Hot and Beautiful 💕 Hosur Escorts call Girls
 
VIP Vapi Call Girls 📞 8617697112 Vapi Call Girls
VIP Vapi Call Girls 📞 8617697112 Vapi Call GirlsVIP Vapi Call Girls 📞 8617697112 Vapi Call Girls
VIP Vapi Call Girls 📞 8617697112 Vapi Call Girls
 
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
🔥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
  • 6. REST API Best Practices
  • 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" }