REST APIs function primarily through the use of resources that are located at a certain URI. A resource could be a file like a text file, html, image, video or dynamic business data.
REST uses various ways to represent a resource like text, JSON or XML. For data, the most common types are JSON or XML.
Representing Resources in the API
A resource in REST can be represented the same way you would create an object in JavaScript (hence JSON) or the same way you structure an entity in a database.
It’s very important that a consistent format is chosen and used throughout the API. If the client sends that they want XML and you support XML all responses even errors should be returned in XML. I prefer to send and receive JSON but either option is perfectly fine with me.
<book>
<id>1</id>
<title>The Art of Computer Programming</title>
<authors>
<author>
<name>Donald Knuth</name>
<id>2</id>
</author>
</authors>
</book>
Here’s how the same resource would potentially be represented in JSON.
{
"id": 1,
"title": "The Art of Computer Programming",
"authors: [{
"name": "Donald Knuth",
"id": 2
}]
}
Resource Modelling
It is the responsibility of the server to respond to requests in a way that the client can understand. When building our resource representation we need to focus on the following things:
- Completeness: the format should be complete and give me everything that I need about the resource without needing to make more api calls.
- Understandable: the client and server should be able to understand one another and use the format that’s being sent.
- Linking – it should be really clear what other resources a resource can link to. The format we design should be able to handle that. REST + HATEOS can be a great architecture for development and reducing maintenance costs.
Resource Naming
All resources should have a plural version of the name unless the resource is a singleton within the system. For example, a configuration resource or maybe the status of the system. Everything in the system should be consistent and predictable.
Endpoints Structured Around Resources
Endpoints (or URI’s) should be structured around the name of the resource. For example, if I was building an ecommerce store I would probably have books, authors, and publishers.
Good example:
https://api.example.com/v1/books – to get all books
https://api.example.com/v1/books/1 – to get a specific book
Poor example:
https://api.example.com/v1/ – gets all books
https://api.example.com/v1/1 – gets a specific book.
Wrapping It Up
How we name our resources and how we restructure our resources has a significant impact on how people will implement it and the potential popularity of it. If the naming is really poor or really inconsistent the business will struggle to get it used.
K.I.S.S. really does apply when designing a RESTful API. Keep it really simple, and consistent and you will likely have great success.