Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • jQuery
  • AngularJS
  • ReactJS
  • Next.js
  • React Native
  • NodeJS
  • Express.js
  • MongoDB
  • MERN Stack
  • PHP
  • WordPress
  • Bootstrap
  • Tailwind
  • CSS Frameworks
  • JS Frameworks
  • Web Development
Open In App
Next Article:
Good Coding Practices For Backend Developers
Next article icon

Best Coding Practices For Rest API Design

Last Updated : 19 Apr, 2022
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication, 

All these words are familiar to you if you are in backend development and you have worked on API (Application Programming Interface). Being a developer you might have worked on some kind of APIs (especially those who are experienced developers). Maybe a payment gateway API, Google Maps API, Sending Email APIs, or any other kind of APIs depending on the type of application and the requirements. 

Best-Coding-Practices-For-Rest-API-Design

Many times it happens that developers read the documentation part of the API, implement it, but they do not focus on building a clean, understandable, and scalable architecture when they are implementing any kind of API in their application. These things impact a system a lot when the application grows with time. 

Consider a scenario that you have built an application and now you need to expose the interface to the user. Do you really think that both of you will be at the same table? Do you think that they will understand the same thing that you're trying to depict in your system? 

When you're building a Restful API it is important to design it properly to avoid any bug or issue in your application. You need to take care of the performance, security, and ease of use for API consumers. It is good to follow some good conventions to build an API that is clean, understandable, and easy to work with. 

There are so many aspects you need to consider when you're building a Restful API in your application. In this blog, we will highlight those aspects in detail. Let's discuss the best coding convention to build the REST API in your application. 

1. Name of the endpoint should be accompanied by the HTTP method

Being a backend developer you might have been familiar with the various HTTP request methods to perform CRUD actions in your application especially the ones, which are common such as GET, POST, PUT, DELETE, and PATCH. In case you are not familiar with these methods then read the blog HTTP Request Methods. 

When you're implementing an API make sure that the name of the endpoints linked with the resources go along with the HTTP method related to the actions you're using in your application. Look at the example given below for reference...

- GET /get_customers
- POST /insert_customers
- PUT /modify_customers
- DELETE /delete_customers
+ GET /customers
+ POST /customers
+ PUT /customers
+ DELETE /customers

2. Return standard error codes according to the result of our API

While implementing an API the endpoints return the result that whether the action is successful or not. The result is always associated with some status code. For example: if you get the status 200 (ok) then it means the result is successful and if you get the status code 400 (bad request) then the result is failed (You can check the response using some tools like Postman to get to know the status code for the actions you perform in your application).

Handle the errors gracefully and return the HTTP response code to indicate what kind of error is generated. This is helpful for API maintainers to understand the issues and troubleshoot them. 

Make sure that you know the existing status code to identify the case you need to apply each one of them. Sometimes it happens that the return message does not match with the status code and that creates confusion for the developers as well as for the consumers who are using that REST API. This is really harmful to the application. So it's good to take care of the status code for the actions you perform in your application. Below is one of the examples...

// Bad, status code 200 (Success)
// associated with an error object
{
    "status": 200,
    "error": {...}
}// Good
{
    "status": 200,
    "data": [...]
}

Some common error codes are given below...

  • 400 Bad Request – Client-side input fails validation.
  • 401 Unauthorized – User isn’t authorized to access a resource. It usually returns when the user isn’t authenticated.
  • 403 Forbidden – User is authenticated, but it’s not allowed to access a resource.
  • 404 Not Found – Resource is not found.
  • 500 Internal server error – Generic server error. It probably shouldn’t be thrown explicitly.
  • 502 Bad Gateway – This indicates an invalid response from an upstream server.
  • 503 Service Unavailable – Something unexpected happened on the server-side (It can be anything like server overload, some parts of the system failed, etc.).

3. Support for the Filter, Sort, and Pagination

How would your server react if you implement an API in your application and the endpoints return the results in millions....???

Your server will be down and it's really going to cry in front of you...(jokes apart...)

Many times it happens that we only need to consume some specific or fewer resources from our server. The reason could be anything. It can be the performance of the system, search system, or the massive amount of information that is not needed to return all at once. You can use a filter to return some specific item based on the condition. If you want to return a few results at a time then use pagination in your API. 

These concepts will help you to display only a specific type of information and it will increase the performance of your system by consuming fewer resources. Examples are given below...

  • Filter: filter the customer with the following properties... the last name is Smith and the age is 30.
    GET /customers?last_name=Smith&age=30
  • Pagination: Return 20 rows starting from 0
    GET /customers?limit=20&offset=0
  • Sort: Return rows sorted by email in the ascendant.
    GET /customers?sort_by=asc(email)

4. Endpoints name should be plural

If you have implemented any kind of API in your application then you might have come across a question that whether the endpoint name should be singular or plural. Remember that you need to maintain consistency throughout your application. So it's good to build the endpoints in the plural to be consistent in your database. 

It's not necessary that you will always get a single item. You can have many items in a table but even if you consider the scenario of getting the result only one and you place it singular everywhere then you won't be able to maintain the consistency in the name of your routes. 

- GET /article
- GET /article/:id
+ GET /articles
+ GET /articles/:id

5. Nesting resources for hierarchical objects

While implementing an API you need to take care of the path for the endpoints. The path of the endpoint deal with the nested resources. To create this path treat the nested resource as the name of the path and append it after the parent resource. Make sure that the nested resource matches the table you have stored in your database else it will create confusion for you. 

If you don't get the above point then understand this in a way that you have a list of students in your database. Each one of them has chosen the subjects they are interested in. Treat the 'subject' table as a child of a 'student' table in your database. 

Now, if you want to create the endpoint for the subjects associated with the student then append the /subjects path to the end of the /student path. If you're using the GET method then an example of the endpoint path will look something like the given below...

'/students/:studentId/subjects'

We get subjects on the students identified by studentId and then the response will be returned. Here, students are the parent's resources and the subject is the child's resources of the student.  So as discussed, we are adding subjects after the '/students/:studentId'. Each student has their own subject. The same kind of nesting structure will be applied to other methods as well such as POST, PUT and DELETE endpoints.

6. Follow good security practices

When you're implementing an API make sure that the communication between the client and the server is private because you often send and receive private information. For security purposes, you can use SSL/TLS.

Using the SSL certificate isn't too difficult. You can easily load it onto the server and the cost of an SSL certificate is also free and very low. Don't make your REST API open. It should communicate over secure channels.

When a user is accessing the information, they shouldn't be able to access more data they have requested. Being a user you are not allowed to access the information of another user or the data of admins. 

To implement the principle of the least privilege, add role checks for a single role or more granular roles for each user. If you want to group users into a few roles then they should be allowed to cover all they need and no more. 

For each feature that users have access to if you have more granular permission then make sure that the admins can easily add and remove those features for each user accordingly. Add some preset roles that can be applied to group users. You won't have to do this for every user manually. 

7. Cache data to increase the performance

You might have used caching during the implementation of some features in your application. Caching is really a powerful tool to speed up the performance of your application. Using caching you will get faster results and you won't have to extract the data from the database multiple times for the same query. 

Use caching during the implementation of your API. It will speed up the performance of your application and it will reduce the consumption of the resources. It's good to cache the data instead of running the same query and asking the database to give the same result (your database will start crying in front of you....lolzzz). 

One of the precautions you need to take care is that you don't get outdated data. Due to the old data, something wrong can happen and your system can generate a lot of bugs in a production environment. Do not keep the information for a long period of time in the cache. It is good to keep the data for a short period of time in the cache. 

Depending on the needs you can change the way data is cached. One of the great services to implement caching is Redis

8. Versioning

Keeping the different versions of your API will help you to track the changes and it will help you to restore the previous version in case if something goes wrong with the latest one. Consider a scenario that you implemented an API, deploy it and a lot of clients start using it. Now at some point, you want to make some changes and you added or removed the data from a resource. 

Chances are there that it will generate bugs on the external services that consume the interface. This is the reason you should keep the different versions of your API. From the previous version, you can get the backup and work on it further. 

Versioning can be done according to the semantic version. Don't force everyone to work on the same version at the same time, you can gradually remove the old versions of your API once you see that it's not required anymore. Most of the time versioning is done with /v1/, /v2/, etc. added at the start of the API path.

GET /v1/customers
GET /v2/students

Conclusion

JSON, SSL/TLS, HTTP Status codes are the standard building blocks of the modern web app API. TO design a high-quality Restful API follow the best conventions we have discussed above. 

Being a backend developer your job is not just to implement the features you are asked to do. You also need to take care of doing it in the best possible way. Apply the best principle when you're implementing an API so that people who consume and work on it as it.


Next Article
Good Coding Practices For Backend Developers

A

anuupadhyay
Improve
Article Tags :
  • GBlog
  • Web Technologies

Similar Reads

    Best Practices For REST API Testing
    REST, or Representational State Transfer, is a type of software architecture that is commonly used for building web services and APIs. A REST API is an application programming interface (API) that uses REST principles to expose data and functionality for client applications to access. REST APIs are
    8 min read
    Good Coding Practices For Backend Developers
    API, Authentication, Design Patterns, MVC, Cache, Cookies, Sessions, JSON, Endpoints, Server, Hosting, Postman, CRUD, Curl...Aren't all these words familiar to you???If yes, then surely you're a backend developer or working on the backend part of the application. Clients often underestimate the work
    9 min read
    7 Best Practices for API Security in 2025
    APIs are the backbone of seamless integration and intercommunication among diverse systems in the dynamic digital world. Nevertheless, connectivity has its setbacks, especially when it comes to issues of increased vulnerability. Cyber-attacks are now more than ever a striking reality, warranting APA
    8 min read
    7 Best Practices for API Security in 2025
    APIs are the backbone of seamless integration and intercommunication among diverse systems in the dynamic digital world. Nevertheless, connectivity has its setbacks, especially when it comes to issues of increased vulnerability. Cyber-attacks are now more than ever a striking reality, warranting APA
    8 min read
    Crafting High-Performance RESTful APIs with ExpressJS
    Building RESTful APIs with Express.js involves setting up a Node.js server using Express, defining routes to handle various HTTP methods (GET, POST, PUT, DELETE), and managing requests and responses with middleware. You can integrate a database like MongoDB for data persistence and implement error h
    4 min read
    10 Interesting APIs to Consider for Projects
    API is an acronym for Application Programming Interface. In simple words, we can say that an API delivers a user response to a system and sends the system's response back to a user. One of the most common examples is weather apps, whenever we search the weather of any specific place the apps do not
    6 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences