Quick Overview:
This blog post sheds light on the REST
(Representational State Transfer) architecture.
We have covered what are the key aspects to
look-into the best API designs, what are the 6
architectural constraints of REST API, and
shared our archived top 12 REST API Best
Practices that help you build robust enterprise
application architecture.
Introduction
What is REST API?
3 Traits For an Ideal RESTful API Design
6 RESTful Architectural Constraints
REST API Best Practices
Conclusion
CONTENTS
1.
2.
3.
4.
5.
6.
Sure, you might be thinking that the REST API
has given no standards or rulebook to follow
when designing your representational state
transfer app interface. However, we at Bacancy
Technology have identified and are practicing
these 9 top best practices for REST API design.
The RESTful system is often restricted by a
uniform interface, code on demand, client-
server architecture, cacheability, client-server
architecture, or statelessness. But this does not
limit the designers because REST is merely a
design approach and not a standard or
framework.
Since the genesis of the restapi approach as
found by Roy Fielding in the year 2000 and over
these 20 years of software development, we
have adapted these REST API best practices
design in 2021. We hope they will turn up to be
helpful to you too.
Let us begin from dawn. For those who want to
get the very idea of the Restful application
programming interface, we’re here with the
definition:
“REST stands for Representational State
Transfer, and it is an application programming
interface. The HTTPs communication protocol
mostly accesses it”.
1. Easy to Work with, Easy to View:
A well-grounded API will be uncomplicated to
work with. Its resources and other related
operations should be quickly committed to
memory by developers who deal with it
consistently. Thus, an ideal API should be
trouble-free to read and write so that designers
and developers are comfortable working with it.
2. Tough to misuse:
Integration with an API having a good design
will be quite straightforward when writing
inaccurate code becomes less likely to occur. It
has knowledgeable feedback and does not
enforce any severe guidelines on the API end
customer.
3. Outright & concise:
With conciseness, we mean that a
comprehensive API will enable developers to
create full-fledged applications in opposition to
your exposed data. Usually, completeness takes
place over time, and maximum API designers
gradually build on top of the existing APIs.
Thus, this is an ideal trait of the best API design
that every organization or an engineer having
an API should be dedicated to.
1. Uniform interface
By REST, you use the same concept to decouple
the client from implementing the REST service.
Compare interface with a contract signed
between client-server where you must use
certain standards. The reason being, globally
accepted APIs should enforce global concepts,
like standards, to make them understandable.
2. Client-server
Here, we mean that the server application and
the client application should evolve individually
without the need to depend on each other. To be
more precise, it should stick to the separation of
concerns. By separation of concerns, the code on
the client end can be modified/altered anytime
without creating any impact on the conditions
of the server. Additionally, the code on the
server end can be altered without altering the
conditions of the client.
By maintaining the separation of concerns, we
can enhance the flexibility and Scalability of the
particular interface across various platforms. A
client must be aware of resource URIs only.
Unless and until the interface between clients
and servers is kept unaltered, they can be
developed and replaced separately.
3. Stateless
Having gained inspiration from HTTP, Roy
fielding considers this constraint. By this
architectural constraint, we mean to make all
the client-server engagements stateless. This
way, the server will not reserve anything
regarding the latest HTTP request made by the
client. Hence, it will consider every request as a
new and unique one. Moreover, it must not rely
on any prior information exchanged between
the two. This further means no session, no
history.
The client is held accountable for handling the
application’s state. A client application requires
a stateful application for the end-user, wherein
the logs in once and carries out various
authorized operations. Every request from the
client must involve all the essential information
for servicing the request and authorization
details and authentication.
4. Cacheable
Today, caching holds vital importance wherever
applicable. With caching comes an enhanced
performance for the client, leading to an
improved scope for scalability for a server with a
reduced load.
When it comes to REST, every response can be
termed as cacheable and non-cacheable. You can
use the cached response as the request-response
instead of checking with the server. This helps in
eliminating the interaction required between
the client and the server up to some extent.
5. Layered system
Generally, components are unable to view
beyond the immediate layer. REST enables you
to make use of a layered architecture system.
Here, you can deploy the APIs on server A, save
data on server B, and verify requests on server C.
These servers may offer a security layer, a load-
balancing layer, a caching layer, and several
other functionalities. Additionally, any of these
layers must not influence the responses or
requests.
6. Code on demand (optional)
This one is generally an optional constraint.
Usually, you will be required to send a static
representation of resources in a JSON REST API
or XML form. However, whenever you need to,
you can easily return executable code for
supporting a vital part of your application.
Below are the 12 assembled REST API Best
Practices design that we implement and have
helped us in our business applications. Check
them out if they might help you as well.
1. Use Nouns and not Verbs in URI
REST APIs must be developed for resources that
can be services, entities, etc. Hence, they should
always consist of nouns and not verbs. This
means that we must refrain from using verbs in
REST endpoint paths. Instead, we must
implement nouns that represent a certain
entity.
Why? Because the HTTP request method that
we use already consists of a verb. Having verbs
in the REST API endpoint path does nothing
and, thus, is unnecessary as it does not fetch
any new information.
The selected verbs can vary from a developer’s
notion. For example, some prefer ‘get’, while
some prefer ‘retrieve’. Hence, it is better to
allow the HTTP GET verb to state what an
endpoint does.
GET, PUT, DELETE, and POST.
GET rectifies and recovers resources
PUT updates the current data
DELETE eliminates data
POST delivers new and unique data to the
server.
The action must be specified by the HTTP
request method made by us. Generally, some
basic methods involve
The verbs map to Create, Read, Update, and
Delete(CRUD) operations. Hence, to get news
articles, you have to create GET /articles/. POST
/articles/ to add a new article, PUT /articles/:id
for updating the article provided by the given
ID, and DELETE /articles/:id to delete an article
provided by the given ID. /articles denote a
REST API example resource.
For example, we can employ Express to
implement these endpoints to manipulate
articles like,
In the code above, you can see that the path
names do not consist of any verbs in them. It
states all nouns and HTTP verbs.
2. Use Plural naming conventions
Usually, we prefer using plurals. However,
know that no rule states one cannot use a
singular when it comes to the resource name.
Here’s why plurals are used:
We are working on one resource from the set of
resources. Hence, to illustrate collection, we
make use of plural naming conventions.
For example, let us consider GET /users/123. The
client here asks to rectify and recover a
resource from the user’s collection with ID 123.
While developing a resource, if we need/wish to
add another resource to the existing collection
of resources, the API looks like POST /users.
3. Hypermedia as the engine of
application state (HATEOAS)
This constraint stands out for several other
network application architectures from the
REST architecture. The Hypermedia As Transfer
Engine Of Application offers easy navigation via
certain resources and their available actions. By
this, a client is not required to know how to
communicate with an application for distinct
actions because each of the metadata gets
embedded in the responses sent from the
server.
For a clearer understanding, let us look at an
example. Here is a response of a retrieved user
having ID 123 from the server.
At times, it is easy and comfortable in skipping
the format of links, thereby specifying links as
fields of a resource given below:
Ideally, it is not a convention that needs to be
followed every time. This is because it relies on
resource size/fields and actions that can be
executed on resources. If resources consist of
multiple fields that users do not wish to go
through, it is better to show navigation to sub-
resources followed by implementing HATEOAS.
Swagger is a popular and widely used tool that
is used to document REST APIs. It offers a way
to analyze the use of a particular API, thereby
enabling developers to be aware of the
fundamental Semantic behavior. To be more
precise, it is an analytical way of incorporating
documentation using annotations that further
gives rise to a JSON that describes APIs and
their usage.
4. Swagger
REST enables using various output formats
such as JSON, RSS, XML, CSV, and HTML.
Although, this entirely depends on what you
require your API for and the application you
possess. If you have a public-facing service that
you wish to be available via REST API design,
you must choose JSON data format. Almost in
99% of cases, JSON is the most preferred data
format for interacting between payload and
response.
To ensure when the REST API design app
responds with JSON, you must set Content-
Type in the header in response to the
application/JSON following the request. Various
server-side app frameworks automatically set
the response header. Few HTTP clients see the
Content-Type response header and review the
data as per the format.
5. Use only JSON
One and the only exception is at times when
you try to exchange files between server and
client. For this, you are required to manage file
resolves and send form data directly from the
client to the server. However, that is a different
topic. All and all, keep in mind that you need to
ensure that your endpoints return JSON REST
API as a response. Several server-side
frameworks own this built-in feature.
6. Allow filtering, sorting, and
pagination
Few key features for consuming API include
filtering, sorting, and paging. Often, resource
collection can be huge. The databases behind
REST API standards can also get enormous.
Eventually, it brings down the performance of
our systems. To eradicate these, we can use,
Filtering: To shrink the query results by
certain parameters. For example, country or
creation date.
Sorting: This enables sorting the results in
an ascending or descending order by a
selected parameter/(s). For example, by
date.
Paging: It uses ‘limit’ to narrow down the
count of results displayed to a certain
number and ‘offset’ to denote the part of the
result range to be displayed. This is
significant in cases where the count of total
outcomes is greater than the ones
introduced.
By pagination data, we ensure returning only a
couple of results instead of collecting all the
requested data at once. By filtering and
pagination, you can elevate the performance as
there is a potential reduction in the usage of
server resources. With more and more data
assembling in the databases, these features
become more important.
7. Performance optimization with
Caching
You can add caching to bring back data from the
local memory cache rather than querying the
database for obtaining the data every time you
wish to retrieve any data requested by the
users. An excellent point of caching is that users
can achieve data even faster. However, many
times, the data achieved by users might be
outdated. Eventually, this can lead to major
problems while debugging in production
environments, as anything might go wrong
because users entertain old data.
There are several types of caching solutions,
such as in-memory caching, Redis, etc. With
this, you can alter the way data is cached as
your requirements change.
For example, Express possesses the api cache
middleware to add cache to the app without
considerable configuration. You can incorporate
an easy in-memory cache to our server such as,
In case you use caching, ensure including
Cache-Control information in headers. This will
assist your users efficiently in using your
caching system.
8. Error Handling
To cut off confusion for all API users, errors
must be handled gracefully, thereby returning
the HTTP response codes that denote the
nature of the error that has occurred. This
provides the API maintainers sufficient
information to analyze the source and cause of
the problem. In case you don’t wish errors to
harm your system, you can leave them
unhandled. This means that the API consumer
has to handle errors.
Here is a list of common error HTTP status
codes. Let’s have a look!
• 400 Bad Requests: This denotes that the
client-side input has failed
documentation/validation.
• 401 Unauthorized: This denotes that the user
is unauthorized for accessing a resource.
Usually, it returns when a user is not verified.
• 403 Forbidden: This denotes that the user is
inappropriate and is not allowed to access a
resource even after being verified.
• 404 Not Found: This denotes that no resources
are found.
• 500 Internal server error: This is a common
server error.
• 502 Bad Gateway: This error marks an
invalid/null response from an upstream server.
• 503 Service Unavailable: This denotes that
something unpredicted and unusual activity
took place on the server-side. (server overload,
part failure, system failure)
Error codes are required to accompany
messages with them so that the API
maintainers can obtain sufficient information
for troubleshooting the issue. However,
attackers cannot utilize the error content for
cyberattacks, such as bringing the system down
or stealing vital information. If your API stays
incomplete, you should send errors along with
information to allow users to take corrective
actions.
Never skip versioning your API. Versioning
enables you to repeat faster, thereby preventing
inapplicable requests to hit updated endpoints.
Alongside, it assists in smoothing over any
complex API version transitions as you can
keep offering old API versions for an extended
period.
Generally, there are mixed reviews regarding
whether an API version must be incorporated in
a header or the URL. Well, if we speak
academically, it must be situated in the header.
However, the version requires to be present in
the REST API URL, thereby ensuring the
exploration of the browser across several
versions, enjoying an easy and simple developer
experience.
9. Versioning
Ideally, an API can never be stable. Hence, it is a
variable. Although the change is unavoidable,
what is important is to look at how to manage
the change. An excellent practice for plenty of
APIs is well-documented and announced
depreciation schedules every month.
Few examples of endpoint URI versioning
include:
• https://api.stripe.com/v1/ (major version
indication only)
• https://us6.api.mailchimp.com/3.0/ (major +
minor version indication)
• https://api.twilio.com/2010-04-01/ (date based
indication)
• https://developer.github.com/v3/ (major
version indication only)
If a resource consists of sub-resources, ensure
depicting this in the API, thereby making it
clear and specific. For instance, if a user has
posts and we wish to retrieve/ redeem a certain
post by the user, API can be interpreted as GET
/users/123/posts/1. This will retrieve the post
having id one by the user having the id 123
.
Many times, resource objects can be linked with
one another or possess some sort of functional
hierarchy. It is usually a better idea to restrict
the nesting to a single level in the REST API. If
you think of implementing too many nested
levels, it might not look elegant. Also, by
filtering, you can achieve a similar result.
10. Resource hierarchy
Some safe methods are HTTP methods that
return the exact resource representation. GET,
TRACE, OPTIONS, and HEAD methods are
referred to as safe. By safe, we mean that they
are ideally expected to retrieve data without
changing the state of a resource on the server.
Moreover, refrain from using GET to delete
content, like GET /users/123/delete.
Generally, it is nothing like it cannot be
executed, but the problem arises because the
HTTP specification gets violated in this case.
Hence, make use of HTTP methods as per the
action that you are required to carry out.
11. Idempotence (Misusing Safe
methods)
Publishing your API documentation is
extremely vital. Not only do these help
developers, but users as well. When you publish
the API documentation, developers view what
they are dealing with while making an
implementation. Besides this, publishing
enables potential users to look into what is
made available through your API.
API Documentation must offer information
regarding the existing methods and endpoints,
potential response codes, request/response
examples, existing throttling or limits, and
information about authorization. An excellent
idea for this is to publish the documentation in
a browsable web page format that has engaging
options, playground, and curl examples.
12. API Documentation
Bear in mind that the API documentation even
represents your organization. A comprehensive,
well-written, and exceptionally presented
document will be acknowledged by the
developers and partners, thereby creating an
example of how it must be created. However, if
a clumsy and poorly designed documentation
that has no examples has plenty of errors and is
outdated, it may eventually harm the image of
your organization.
Some excellent examples of API documentation
are,
• Mailchimp
• Twilio
• Stripe
The chief takeaway required to design a high-
quality REST API standards is maintaining
consistency by sticking to conventions and web
standards. Developers are required to devote a
good time to design REST APIs. Why? Because
APIs hold the capacity to turn any service
extremely easy or extremely complicated.
When it comes to the modern web, JSON, HTTP,
SSL/TLS status codes are some standard
building blocks. As a quick wrap-up, we need to
put focus on performance as well. To elevate
performance, make sure you don’t return too
much data simultaneously. With caching, you
don’t need to query for data each time.
Additionally, maintain consistency in the paths
of endpoints. This was a guide that states the
top REST API best practices. Looking for
explicit REST API architecture designers,
Bacancy Technology is the right window for
your business.