SlideShare a Scribd company logo
{API} Design Best Practices
PRAKASH BHANDARI
Software Engineer
What is an API in simple terms?
API stands for Application Programming Interface.
It allows two applications to communicate with one
another to access data.
Image source : https://automatedbuildings.com/news/sep19/articles/cochrane/190822114303cochrane.html
How applications communicate with one another
to access data?
Gives clients the power to ask for exactly
what they need and nothing more, makes it
easier to evolve APIs over time, and enables
powerful developer tools.
Today we will focus on REST API
GRAPH QL
1. Use proper HTTP Methods
HTTP methods serve the purpose of explaining CRUD functionality.
1 2 3 4 5
2. Accept and respond with JSON
Always validate the content-type and if you want to go with a default
one use content-type: application/json
3. Use kebab-case for URLs
BAD GOOD
Camel case
1 /generatePageThumbnails
Snake case
2 /generate_page_thumb
nails
Kabab case
3 /generate-page-
thumbnails
4. Use ‘Plural Name’ to point to a collection
BAD GOOD note
Singular name
1 /file
Singular name
2 /File
Plural name
3 /files
More info: https://restfulapi.net/resource-naming/
5. Don’t use `verbs` to explain operation in
resourceful URLs
BAD GOOD note
Function itself explaining
what it’s doing.
1 POST
/updateStory
Function itself explaining
what it’s doing.
2 GET /getStory
HTTP method is explaining
what's it’s doing.
3 GET
/stories/{storyId}
Use proper HTTP method to explain the operation for
resourceful URLs (can be done via CURD)
6. `verbs` can be used for non-resourceful URLs
BAD GOOD note
HTTP method is explaining
what's it’s doing.
1 POST
/notifications/{user
Id}/resend
If the function is not doing any CURD operation than we can use verbs
in our non
-resourceful APIs
7. Use simple `Ordinal Number` to version the API
BAD GOOD note
Ordinal number in api
version
1 /v1/files
Don’t modify the existing APIs if it has major changes.
Always create a version of API because it can be used by external entities (more on
next slide). Change might break their functionality.
Ordinal number in api
version
2 /v2/files
Ordinal number in api
version
3 /v1.1/files
Don’t use word numbers
4 /one/files
Don’t use pure number in
api version
5 /1/files
7.1 Why API Versioning?
https://app.example.com/api/v3.2.3/users
Refer to this article for more information.
9. Allow filtering, sorting, and pagination
Filtering and pagination both increase performance by reducing the usage of server
resources. As more data accumulates in the database, the more important these
features become
/users?lastName=Smith&age=30&sort=-lastName,-createdAt&offset=1&limit=1
{
[
{
"firstName":"John",
"lastName":"Smith",
"age":30
}
],
total:2
}
Where `+` means ascending and `-` means descending. So we sort by users -
lastName in alphabetical order and createdAt from most recent to least recent.
Also URL pram should be
camelCase and JSON property
10. Take fields Query Parameter
The amount of data being returned should also be taken into consideration. Add a
fields parameter to expose only the required fields from your API.
Example:
Only return the id, name, description, and url of the file.
GET /files?fields=id,name,description,url
It also helps to reduce the response size in some cases.
11. Use the Relation in the URL For Nested Resources
The amount of data being returned should also be taken into consideration. Add a
fields parameter to expose only the required fields from your API.
Example:
1. GET /stories/1/files : Get the list of all files from story 1.
2. GET /stories/1/files/2: Get the details of file 2, which belongs to story 1.
3. DELETE /stories/1/files/2 : Should delete file 2, which belongs to story 1.
4. PUT /stories/1/files/2 : should update the file info of 2.
13. Handle errors gracefully and return standard
error codes
To eliminate confusion for API users when an error occurs, we should handle errors
gracefully and return HTTP response codes that indicate what kind of error occurred.
This gives debugger of the API enough information to understand the problem that’s
occurred.
14. Maintain good documentation and Use API
design tools
Having good and detailed documentation results in a great user experience for your
API consumers.
● Improved User Adoption
● Increased Awareness
● Saves Support Time and Costs
● Easier Maintenance
● Versioning is more streamlined
Use API design tools:
15. Use best security practices
1. Don’t Pass Authentication Tokens in URL
GET /files/1/token={token}
Instead, pass them with the header: Authorization: Bearer {token}
1. Handle CORS properly
2. Enforce HTTPS (TLS-encrypted)
3. API Rate limiting
4. Input validations and sanitization (Define an implicit input validation by using
strong types like numbers, booleans, dates, times, or fixed data ranges in API
parameters.)
More on : https://dzone.com/articles/security-best-practices-for-rest-apis
16. Rate limiting (Throttling)
Throttling to prevent your API from being overwhelmed by too many requests. It is
standard practice to add some sort of rate limiting to an API. Return a HTTP status
code 429 for too many requests
RFC 6585 introduced a HTTP status code 429 Too Many Requests to accommodate
this.
Example : Amazon API gateway uses rate limiting while calling lambda function.
17. Cache data to improve performance
We can add caching to return data from the local memory cache instead of querying
the database to get the data every time we want to retrieve some data that users
request.
The good thing about caching is that users can get data faster.
However, the data that users get may be outdated. This may also lead to issues when
debugging in production environments when something goes wrong as we keep
seeing old data. There are many kinds of caching solutions like:
● Redis,
● Memcache
● and more.
Conclusion
1 2
References
1. https://aviyel.com/post/225/best-practices-for-api-design
2. https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/#h-accept-and-
respond-with-json
3. https://www.slideshare.net/SpencerSchneidenbach/restful-api-design-best-practices-using-
aspnet-web-api
4. https://developer.mindsphere.io/concepts/concept-api-versioning.html
5. https://restfulapi.net/resource-naming/
6. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429
7. https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-
Resource-Sharing-for-REST-APIs/
API Design-   Best Practices

More Related Content

What's hot

REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debateRestlet
 
Identity management and single sign on - how much flexibility
Identity management and single sign on - how much flexibilityIdentity management and single sign on - how much flexibility
Identity management and single sign on - how much flexibilityRyan Dawson
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding RESTNitin Pande
 
Architecting an Enterprise API Management Strategy
Architecting an Enterprise API Management StrategyArchitecting an Enterprise API Management Strategy
Architecting an Enterprise API Management StrategyWSO2
 
API Security Best Practices & Guidelines
API Security Best Practices & GuidelinesAPI Security Best Practices & Guidelines
API Security Best Practices & GuidelinesPrabath Siriwardena
 
Getting Started with API Security Testing
Getting Started with API Security TestingGetting Started with API Security Testing
Getting Started with API Security TestingSmartBear
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityMohammed Fazuluddin
 

What's hot (20)

REST API Basics
REST API BasicsREST API Basics
REST API Basics
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
 
Identity management and single sign on - how much flexibility
Identity management and single sign on - how much flexibilityIdentity management and single sign on - how much flexibility
Identity management and single sign on - how much flexibility
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
Architecting an Enterprise API Management Strategy
Architecting an Enterprise API Management StrategyArchitecting an Enterprise API Management Strategy
Architecting an Enterprise API Management Strategy
 
Web api
Web apiWeb api
Web api
 
API Presentation
API PresentationAPI Presentation
API Presentation
 
Deep-Dive: Secure API Management
Deep-Dive: Secure API ManagementDeep-Dive: Secure API Management
Deep-Dive: Secure API Management
 
API Security Best Practices & Guidelines
API Security Best Practices & GuidelinesAPI Security Best Practices & Guidelines
API Security Best Practices & Guidelines
 
Api security-testing
Api security-testingApi security-testing
Api security-testing
 
Apigee Products Overview
Apigee Products OverviewApigee Products Overview
Apigee Products Overview
 
OAuth2 + API Security
OAuth2 + API SecurityOAuth2 + API Security
OAuth2 + API Security
 
REST full API Design
REST full API DesignREST full API Design
REST full API Design
 
Getting Started with API Security Testing
Getting Started with API Security TestingGetting Started with API Security Testing
Getting Started with API Security Testing
 
Amazon API Gateway
Amazon API GatewayAmazon API Gateway
Amazon API Gateway
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API Security
 
API
APIAPI
API
 
Amazon API Gateway
Amazon API GatewayAmazon API Gateway
Amazon API Gateway
 

Similar to API Design- Best Practices

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 APIsAparna Sharma
 
Rest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookRest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookKaty Slemon
 
The ultimate api checklist by Blendr.io
The ultimate api checklist by Blendr.ioThe ultimate api checklist by Blendr.io
The ultimate api checklist by Blendr.ioBlendr.io
 
Session 8 Android Web Services - Part 1.pdf
Session 8 Android Web Services - Part 1.pdfSession 8 Android Web Services - Part 1.pdf
Session 8 Android Web Services - Part 1.pdfEngmohammedAlzared
 
A Deep Dive into REST API Framework Survey
A Deep Dive into REST API Framework SurveyA Deep Dive into REST API Framework Survey
A Deep Dive into REST API Framework SurveyIRJET Journal
 
6 Best Practices that Make a Great API .pdf
6 Best Practices that Make a Great API .pdf6 Best Practices that Make a Great API .pdf
6 Best Practices that Make a Great API .pdfExpert App Devs
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfAparna Sharma
 
APIs_ An Introduction.pptx
APIs_ An Introduction.pptxAPIs_ An Introduction.pptx
APIs_ An Introduction.pptxAkashThorat25
 
Documenting REST APIs
Documenting REST APIsDocumenting REST APIs
Documenting REST APIsTom Johnson
 
Moving into API documentation writing
Moving into API documentation writingMoving into API documentation writing
Moving into API documentation writingEllis Pratt
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfAparna Sharma
 
Business Applications Integration In The Cloud
Business Applications Integration In The CloudBusiness Applications Integration In The Cloud
Business Applications Integration In The CloudAnna Brzezińska
 

Similar to API Design- Best Practices (20)

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
 
Api Testing
Api TestingApi Testing
Api Testing
 
Api Testing
Api TestingApi Testing
Api Testing
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
 
Rest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookRest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbook
 
The ultimate api checklist by Blendr.io
The ultimate api checklist by Blendr.ioThe ultimate api checklist by Blendr.io
The ultimate api checklist by Blendr.io
 
Session 8 Android Web Services - Part 1.pdf
Session 8 Android Web Services - Part 1.pdfSession 8 Android Web Services - Part 1.pdf
Session 8 Android Web Services - Part 1.pdf
 
Web services - REST and SOAP
Web services - REST and SOAPWeb services - REST and SOAP
Web services - REST and SOAP
 
A Deep Dive into REST API Framework Survey
A Deep Dive into REST API Framework SurveyA Deep Dive into REST API Framework Survey
A Deep Dive into REST API Framework Survey
 
6 Best Practices that Make a Great API .pdf
6 Best Practices that Make a Great API .pdf6 Best Practices that Make a Great API .pdf
6 Best Practices that Make a Great API .pdf
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
 
APIs_ An Introduction.pptx
APIs_ An Introduction.pptxAPIs_ An Introduction.pptx
APIs_ An Introduction.pptx
 
Documenting REST APIs
Documenting REST APIsDocumenting REST APIs
Documenting REST APIs
 
Api manager preconference
Api manager preconferenceApi manager preconference
Api manager preconference
 
ReSTful API Final
ReSTful API FinalReSTful API Final
ReSTful API Final
 
APITalkMeetupSharable
APITalkMeetupSharableAPITalkMeetupSharable
APITalkMeetupSharable
 
EBSCoupaIntegration
EBSCoupaIntegrationEBSCoupaIntegration
EBSCoupaIntegration
 
Moving into API documentation writing
Moving into API documentation writingMoving into API documentation writing
Moving into API documentation writing
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
 
Business Applications Integration In The Cloud
Business Applications Integration In The CloudBusiness Applications Integration In The Cloud
Business Applications Integration In The Cloud
 

Recently uploaded

Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion Clinic
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsGlobus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfMeon Technology
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageGlobus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisNeo4j
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024Ortus Solutions, Corp
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessWSO2
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfAMB-Review
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownloadvrstrong314
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
 

Recently uploaded (20)

Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 

API Design- Best Practices

  • 1. {API} Design Best Practices PRAKASH BHANDARI Software Engineer
  • 2. What is an API in simple terms? API stands for Application Programming Interface. It allows two applications to communicate with one another to access data. Image source : https://automatedbuildings.com/news/sep19/articles/cochrane/190822114303cochrane.html
  • 3. How applications communicate with one another to access data? Gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. Today we will focus on REST API GRAPH QL
  • 4. 1. Use proper HTTP Methods HTTP methods serve the purpose of explaining CRUD functionality. 1 2 3 4 5
  • 5. 2. Accept and respond with JSON Always validate the content-type and if you want to go with a default one use content-type: application/json
  • 6. 3. Use kebab-case for URLs BAD GOOD Camel case 1 /generatePageThumbnails Snake case 2 /generate_page_thumb nails Kabab case 3 /generate-page- thumbnails
  • 7. 4. Use ‘Plural Name’ to point to a collection BAD GOOD note Singular name 1 /file Singular name 2 /File Plural name 3 /files More info: https://restfulapi.net/resource-naming/
  • 8. 5. Don’t use `verbs` to explain operation in resourceful URLs BAD GOOD note Function itself explaining what it’s doing. 1 POST /updateStory Function itself explaining what it’s doing. 2 GET /getStory HTTP method is explaining what's it’s doing. 3 GET /stories/{storyId} Use proper HTTP method to explain the operation for resourceful URLs (can be done via CURD)
  • 9. 6. `verbs` can be used for non-resourceful URLs BAD GOOD note HTTP method is explaining what's it’s doing. 1 POST /notifications/{user Id}/resend If the function is not doing any CURD operation than we can use verbs in our non -resourceful APIs
  • 10. 7. Use simple `Ordinal Number` to version the API BAD GOOD note Ordinal number in api version 1 /v1/files Don’t modify the existing APIs if it has major changes. Always create a version of API because it can be used by external entities (more on next slide). Change might break their functionality. Ordinal number in api version 2 /v2/files Ordinal number in api version 3 /v1.1/files Don’t use word numbers 4 /one/files Don’t use pure number in api version 5 /1/files
  • 11. 7.1 Why API Versioning? https://app.example.com/api/v3.2.3/users Refer to this article for more information.
  • 12. 9. Allow filtering, sorting, and pagination Filtering and pagination both increase performance by reducing the usage of server resources. As more data accumulates in the database, the more important these features become /users?lastName=Smith&age=30&sort=-lastName,-createdAt&offset=1&limit=1 { [ { "firstName":"John", "lastName":"Smith", "age":30 } ], total:2 } Where `+` means ascending and `-` means descending. So we sort by users - lastName in alphabetical order and createdAt from most recent to least recent. Also URL pram should be camelCase and JSON property
  • 13. 10. Take fields Query Parameter The amount of data being returned should also be taken into consideration. Add a fields parameter to expose only the required fields from your API. Example: Only return the id, name, description, and url of the file. GET /files?fields=id,name,description,url It also helps to reduce the response size in some cases.
  • 14. 11. Use the Relation in the URL For Nested Resources The amount of data being returned should also be taken into consideration. Add a fields parameter to expose only the required fields from your API. Example: 1. GET /stories/1/files : Get the list of all files from story 1. 2. GET /stories/1/files/2: Get the details of file 2, which belongs to story 1. 3. DELETE /stories/1/files/2 : Should delete file 2, which belongs to story 1. 4. PUT /stories/1/files/2 : should update the file info of 2.
  • 15. 13. Handle errors gracefully and return standard error codes To eliminate confusion for API users when an error occurs, we should handle errors gracefully and return HTTP response codes that indicate what kind of error occurred. This gives debugger of the API enough information to understand the problem that’s occurred.
  • 16. 14. Maintain good documentation and Use API design tools Having good and detailed documentation results in a great user experience for your API consumers. ● Improved User Adoption ● Increased Awareness ● Saves Support Time and Costs ● Easier Maintenance ● Versioning is more streamlined Use API design tools:
  • 17. 15. Use best security practices 1. Don’t Pass Authentication Tokens in URL GET /files/1/token={token} Instead, pass them with the header: Authorization: Bearer {token} 1. Handle CORS properly 2. Enforce HTTPS (TLS-encrypted) 3. API Rate limiting 4. Input validations and sanitization (Define an implicit input validation by using strong types like numbers, booleans, dates, times, or fixed data ranges in API parameters.) More on : https://dzone.com/articles/security-best-practices-for-rest-apis
  • 18. 16. Rate limiting (Throttling) Throttling to prevent your API from being overwhelmed by too many requests. It is standard practice to add some sort of rate limiting to an API. Return a HTTP status code 429 for too many requests RFC 6585 introduced a HTTP status code 429 Too Many Requests to accommodate this. Example : Amazon API gateway uses rate limiting while calling lambda function.
  • 19. 17. Cache data to improve performance We can add caching to return data from the local memory cache instead of querying the database to get the data every time we want to retrieve some data that users request. The good thing about caching is that users can get data faster. However, the data that users get may be outdated. This may also lead to issues when debugging in production environments when something goes wrong as we keep seeing old data. There are many kinds of caching solutions like: ● Redis, ● Memcache ● and more.
  • 21. References 1. https://aviyel.com/post/225/best-practices-for-api-design 2. https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/#h-accept-and- respond-with-json 3. https://www.slideshare.net/SpencerSchneidenbach/restful-api-design-best-practices-using- aspnet-web-api 4. https://developer.mindsphere.io/concepts/concept-api-versioning.html 5. https://restfulapi.net/resource-naming/ 6. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 7. https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin- Resource-Sharing-for-REST-APIs/