0% found this document useful (0 votes)
4 views24 pages

Designing RESTful Web APIs with ROA/D

This document outlines the ROA/D methodology for designing RESTful web APIs, emphasizing the importance of resource-oriented analysis and design. It details the phases of a RESTful project, including inception, elaboration, construction, and transition, while highlighting the iterative nature of the development process. The document serves as a guide for successfully implementing RESTful applications using the Restlet Framework, focusing on requirements gathering, analysis, and solution design.

Uploaded by

Ishka Insaf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

Designing RESTful Web APIs with ROA/D

This document outlines the ROA/D methodology for designing RESTful web APIs, emphasizing the importance of resource-oriented analysis and design. It details the phases of a RESTful project, including inception, elaboration, construction, and transition, while highlighting the iterative nature of the development process. The document serves as a guide for successfully implementing RESTful applications using the Restlet Framework, focusing on requirements gathering, analysis, and solution design.

Uploaded by

Ishka Insaf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D

&

ROA/D&
Designing'a'RESTful'web'API'

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !2

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link]
!
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D'
!
Introduction! 2!
1. Succeeding in a RESTful project: the ROA/D methodology! 2!
1.1 Introducing Resource-Oriented Analysis & Design (ROA/D)! 2!
1.2 Incepting the project! 5!
1.3 Elaborating the solution! 5!
1.4 Constructing the solution! 5!
1.5 Transitioning the project! 5!

2. Gathering requirements! 6!
2.1 Collecting requirements from the sources! 6!
2.2 Classifying requirements by priority! 6!
Priority 1: Core requirements! 6!
Priority 2: Getting users organized! 7!
Priority 3: Integration with classical mail ! 7!

3. Analyzing requirements! 7!
3.1 Describing usage scenarios! 8!
3.2 Defining the domain model! 9!
3.3 Describing system sequences! 10!

4. Designing the solution! 11!


4.1 Defining the logical architecture! 12!
4.2 Deriving the resource model! 14!
4.3 Identifying and classifying the resources! 14!
4.4 Defining the URI space! 15!
Each URI identifies a particular resource! 15!
Crafting your URIs! 16!
URIs identify things, not actions! 17!
The query is a first class URI element! 18!
URIs allow your system to become part of the web! 18!
4.5 Defining allowed methods! 18!
Use HTTP methods properly! 18!
Consider each resource class! 19!
4.6 Defining response statuses! 20!
4.7 Defining representation classes! 22
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D

!
Introduction &
In this document you will learn:

▪ How to succeed in a RESTful project


▪ How to design a RESTful web API with the ROA/D methodology

!
REST introduces a new paradigm for distributed systems. You might still feel unfamiliar with it and have many
questions on how you could use it for your own projects. You might even have the feeling of coming late to the
party, having to catch up with yet another huge set of concepts and techniques others are already mastering. So
we think it’s time to share a little secret with you, which is also good news: you are not late; in fact, you’re among
the first ones.
This is one of the most exciting aspects of the current dynamic around REST: we are witnessing the discovery
and refinement of what makes the Web so powerful and how it can be used for new things, in particular in the field
of enterprise computing (integration, cloud computing, mobile Web, semantic Web and more). We are at the
beginning of mass adoption of REST in these domains, and there are a lot of fascinating discussions and
innovations happening in the REST space, much like during the early years of object-oriented programming.
Researchers and practitioners around the world are proposing and discussing REST design and development
practices, aware that some of them will be keys to the future of the Web. Even better, many of these discussions
and developments are public and you can take part in them or benefit from them in your own projects.
To that end, we will look at RESTful web projects from a methodological perspective. We will not cover Restlet
specifically here: our goal is to give you guidance on how to carry on projects involving REST and how to design
RESTful web APIs. The meat of the matter is the presentation of ROA/D, a pragmatic project methodology
dedicated to Resource-Oriented Analysis & Design. ROA/D is based on our consulting experience at Restlet SAS
since 2008, helping our customers to design their RESTful web APIs and on the feedback of users in the Restlet
community.
We will start with an introduction to ROA/D, giving an overview of the four main phases of a project, which are
composed of iterations over a number of steps. Along the road, we will detail each step of the methodology by
providing guidance and best practices, leveraging UML for the visual communication. We will illustrate major
concepts and practices around an example: a RESTful email system.

1. Succeeding in a RESTful project: the ROA/D methodology


Choosing the Restlet Framework to build your next web Application will take you a long way toward successfully
using REST. This is the purpose of a framework after all, to make sure that the right things are easy to do and offer
the necessary tooling.
Restlet is perfect to implement RESTful applications. However, as you can create Java programs that break all
object-oriented principles, you can also create Restlet programs that break all REST principles. We need additional
guidance, not software, to reach our goal.
In this section, we discuss the impact of REST on project development practices and explain why it requires us
to change our development practices. Then, we introduce the ROA/D methodology and highlight its similarities and
differences with common methodologies such as OOA/D. Finally, we review usual project phases to see where
REST, Restlet and ROA/D matter the most.

1.1 Introducing Resource-Oriented Analysis & Design (ROA/D)


You've hopefully felt the disruptive nature of REST and understand why REST forces us to rethink web
development. REST requires us to think in resources instead of objects in the object-oriented world or tables in the
relational world. Those resources are identified by URIs, hyperlinked together and expose various representations
of their state. They also offer a uniform way to interact with them, mainly via the HTTP standard methods (GET,
PUT, DELETE, POST, etc.).

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !2
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
Designing a RESTful web API while providing useful features to its users isn’t trivial. It requires special skills to
understand the problem domain, analyze the requirements and design the set of resources composing the API.
Let’s take this opportunity to illustrate in figure 1 how we position the RESTful web API.

!
Figure 1 - Overview of a RESTful web API

We define a RESTful web API as a set of hyperlinked resources, forming a subset of the Web, exposed by a web
service or a web site and consumed by web clients. Defining this API is not easy and requires you to:

▪ Analyze the requirements of your web project, the features to provide.


▪ Design the set of resources, their granularity, their URI, the content and structure of their representations,
the standard methods that they expose (maybe depending on the user’s role) or the hyperlinks between
themselves.

Of course, once you have your API defined you can:

▪ Implement it using technologies like Restlet Framework.


▪ Test it to make sure it satisfies requirements and doesn’t break in the future
▪ Deploy it so that your users can actually use it.
That’s a lot of work ahead and you need to be well organized to succeed. To guide you during this journey, we
propose you use ROA/D, a methodology that ensures that you won't miss important steps during your RESTful web
projects. Of course, we didn’t reinvent the wheel and ROA/D fits nicely into popular development processes such as
SCRUM, XP (eXtreme Programming) or UP (Unified Process). All those processes are very iterative in nature as
opposed to the classic waterfall processes. Each of those project iterations is composed of a set of steps as
illustrated in figure 2.
!!
!!
!!

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !3
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D

!
Figure 2 - Typical project iteration steps

Of course, the earlier you are in a project, the more important the first steps (requirements gathering,
requirements analysis and solution design) are. As you move forward in your project, requirements and design
should become more and more stable. Instead, your focus will shift more on the later steps (design implementation
and implementation testing). Finally, during the last iterations you should have successfully deployed your project
into production and ensure that users are using it successfully.
In figure 3 below, we illustrate traditional project phases that every software development project follows,
more or less formally. Of course, RESTful projects are no exception and also follow this series of phases.

!
Figure 3 - Typical project phases defined byUP

Even if those phases are sequential, they keep a very iterative nature. Several iterations will likely be necessary
during each phase, with a shifting focus from requirements, analysis and design during inception and elaboration
phases, toward a focus on implementation and testing during construction and transition phases. As you move
from the beginning to the end of this process, your project should get more and more stable, encouraging early
feed-back and addition of requirements, while giving opportunities for features scope reduction in order to meet
project goals in terms of time and budget.
As its name implies, the ROA/D methodology is especially valuable during the inception and elaboration phases
when you progressively define and stabilize your RESTful web API. On the other hand, the usage of the Restlet
Framework progressively increases to reach a peak during the construction phase. This methodology is basically an
adaptation of the popular OOA/D (Object-Oriented Analysis and Design) methodology to RESTful application
development.

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !4
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
If you are interested to learn more about OOA/D, we highly recommend the book of Craig Larman titled
"Applying UML and Patterns, An Introduction to Object-Oriented Analysis and Design and Iterative
Development" [1]. Considering that Restlet is an object-oriented framework to implement resource-oriented
designs in Java, OOA/D skills are very valuable in addition to ROA/D ones to succeed in your REST project.
While applying ROA/D, we also use UML (Unified Modeling Language) as the recommended visual
communication language instead of inventing yet another visual notation. This gives us the opportunity to clarify a
common misconception: UML is neither a methodology nor a development process; it is different from OOA/D,
ROA/D, SCRUM, XP and UP but also complementary with them. UML is a standardized visual diagramming notation
that facilitates the communication between participants in a software project. It facilitates the representation and
sharing of your models, which is extremely important, but doesn’t say if your models are good or bad.
In the following subsections, we review each phase of a typical ROA/D project.

1.2 Incepting the project


During inception, the project vision should be defined, more or less formally, producing a business case and a set
of initial requirements. Those requirements will be refined during the next phases. At this point, we are looking for
an overall feature scope and main use cases.
This phase is also a good time to clarify the overall timeframe and budget of the project, assess its technical
feasibility (for example proof of concepts prototypes, UI sketches and a logical architecture) and financial feasibility
(for example buy-or-build decision and ROI estimates for example). At the end of this phase, you should decide
whether or not to continue, and in which conditions.

1.3 Elaborating the solution


During the elaboration phase, you identify the majority of the requirements, define a domain model, detail the
logical architecture and reduce the main risks, making sure that the team is properly trained and organized.
Again, this is a phase where several iterations should happen, especially due to the unstable state of the
project. It is a great time for analysis and design workshops, technical prototypes that form reusable subsets of the
final system. This is clearly the phase where the ROA/D methodology is the most useful as your RESTful web API is
specified with a good level of details and your Restlet-based architecture is in place.
At the end of this phase, you should have a clear idea of the amount of effort remaining and the resources
needed to successfully complete the system and deliver the project.

1.4 Constructing the solution


At the beginning of this phase, most of the uncertainties should have disappeared and the team should be ready to
efficiently implement the remaining features of the project. It should be a time of active coding (using the Restlet
Framework, APISpark or a similar technology) and steady progress.
There is still a good chance to have changes in scope and requirements along the way, but their impact should
now be marginal. Otherwise, it means that the elaboration phase wasn't correctly followed; maybe by lack of time
or because the external environment forced in some changes that couldn't be correctly taken into account at that
point.
Again, the iterative nature of the process should ensure you that you identify blocking issues as early as
possible. At the end of this phase, all the features of the project should have been completely developed and the
quality level should be quite good already.

1.5 Transitioning the project


Finally, the project should follow final rounds of testing, bug fixing and get deployed in production. At this point, no
new feature should be added, the code base should be frozen and only fixes should be made after peer review.
This is also a phase where the migration procedures from the previous solution, if existing, should be tested
and, finally, executed. Users should also receive the proper training to ensure a smooth adaptation without too
much impact on their productivity.

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !5
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
Each of the phases we just described is composed of iterations over a number of steps, (we took a look at them
earlier in figure 2). Let’s now examine these steps for a typical ROA/D iteration, one by one starting from the
fundamental requirement-gathering step.

2. Gathering requirements
During the first step of a ROA/D iteration, we collect, write and organize the requirements of an application.

2.1 Collecting requirements from the sources


Gathering requirements is essential because it is the basis of the agreement between users and developers. As
they should be understandable by the users, they should be as free as possible of implementation details; the goal
is to define the "What" and not the "How”. Frequently, users come up with a solution to the problem they face, but
it is essential to discuss and understand the real issue as the naïve solution might not be the best in the end.
In an ideal world, all requirements would be known and described in advance, before the next steps begin and
during the project inception. In practice, those requirements are initially incomplete and evolve during the
inception and elaboration phases to stabilize during the construction phase. Each of the iterations gives an
opportunity to validate, refine or remove the requirements, especially when users can test or react to proposed
solutions.
When we thought about an example application, we wanted to find a domain that everyone would be familiar
with and a problem where REST would be a particularly good fit. One of the most successful Internet applications
has been the email. Its principle is simple: allow the asynchronous exchange of messages between people or
programs across the Internet. The SMTP protocol is used to exchange email messages and the POP protocol to
retrieve them from email boxes. Both protocols were defined in the 1980’s, well before the HTTP protocol that now
powers the Web.

2.2 Classifying requirements by priority


As deliverable of these steps you should get a list of textual requirements, ordered by priority. Note that
requirements are also sometimes called stories to underline their descriptive nature of the intended behavior of the
application.
It’s now time to look at the requirements of our example project. As it would take too much space to describe
all project iterations, we only show you the result. Hereafter we present the result obtained after the inception
phase. We identified more than 20 requirements that we classified in three priority groups.

PRIORITY 1: CORE REQUIREMENTS


First we described the foundation of our application, the core concepts and needs on which more advanced
requirements are defined.

1. Mails are textual messages exchanged between a sender and receivers

2. Mails are composed of a subject, a date and a textual body

3. Mails can have the following statuses: draft, sending, sent, receiving or received

4. Contacts are records about potential mail receivers

5. Mail addresses are defined using HTTP URIs

6. Contacts are composed of a name and a mail address

7. Several accounts can be associated to a single user, called the owner

8. Accounts contain the mails and contacts of their unique owner

9. Mail servers manage several accounts

[Link] can have two roles: application administrator and account owner

[Link] can create and delete accounts

[Link] least one user with an administrator role exists

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !6
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
PRIORITY 2: GETTING USERS ORGANIZED
With the core requirements, we can build a RESTful mail server. However, in order to make it usable by end
users, we need to add a series of requirements. Some of them are illustrated in the figure 4 below,
providing an overview of our RESTful mail system.

!
Figure 4 - Overview of our RESTful mail system

[Link] boxes can be accessed and managed by their owners from a simple mail client (like a regular HTML
browser), a rich mail client (like an AJAX web browser) or from a mobile mail client (like a smartphone).

[Link] can be marked by the owner with any number of textual tags

[Link] statuses are managed using application tags

[Link] owners can create web feeds tracking the latest mails with a given set of tags

[Link] contain the feeds of their owners

PRIORITY 3: INTEGRATION WITH CLASSICAL MAIL


In order the make our mail system usable in an existing context, we need to provide gateways to the classic mail
system. This is the purpose of this final series of requirements.

[Link] can also contain a classical mail address ("name@[Link]")

[Link] can be sent using the classical SMTP protocol when a contact has no URI address

[Link] can be received using the classical SMTP protocol and associated to a mail box

[Link] can be retrieved from remote servers via the classical POP3 protocol

[Link] can be exposed using the FOAF language, providing a mapping to their SMTP mail address in
addition to their URI address

Now that we have gathered requirements, we can move to the next step, which consists in analyzing them.

3. Analyzing requirements
We can now go to the next step of a ROA/D iteration and analyze collected requirements in order to understand the
problem domain and present them as more practical artifacts. The goal is to investigate and describe how the
system will be used and what its main functions are. Analysis can also be helpful to identify additional
requirements.

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !7
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
In this section, we cover the tasks that are typically done during the analysis steps. Of course, this is only a
high-level description and we recommend that you consult more complete references such as the “Applying UML
and Patterns” book from Craig Larman [1]:

▪ Describe the main usage scenarios, with UML use case diagrams
▪ Define the domain model, with UML class diagrams
▪ Describe the main system sequences, with UML sequence diagrams

3.1 Describing usage scenarios


To explain what we expect from a system, it is useful to describe how we will interact with it, like a black box.
For this purpose, we define main usage scenarios in text and illustrate them with UML use case diagrams. Those
diagrams describe interactions between the RESTful mail system and the outside world, the external actors. While
reading the requirements, we identified these actors: mail senders, receivers, account owners and administrators.
The first use case in the figure 5 below shows an interaction between a mail sender and receivers using our
system. At first sight, it looks trivial, but it is important to describe the evident things in order to coin key
terminology and ensure that we don't lose the overall picture of the system.

!
Figure 5 – Sender exchanging an email with receivers

Now, before effectively exchanging emails, it is essential to be able to manage our mail application. This is the
role of the administrators, as illustrated in figure 6. Those power users can create new accounts, grant them roles
and delete them.

!
Figure 6 – System administrator managing accounts

As explained in the requirements, an account is associated to one and only one user, but that doesn't prevent a
user to own several accounts. Now, let's focus on the interactions between an account owner and the mail system
illustrated in figure 7.
!

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !8
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D

!
Figure 7 - Account owner composing mails, managing web feeds, contacts and received mail

An account owner composes new mails by connecting to the system using a mail client, creating a draft mail
and entering the receivers, the subject and the message. He can write his message in several shots, saving draft
mails and editing them again later. Once satisfied with a draft, he can ask the mail server to send the mail. We
present in section 3.3 what exactly happens when a mail is sent out using a system sequence diagram.
Then, he can consult the mailbox and select mails he wants to read, associating tags to stay organized. The
mail status is also exposed via special tags. Finally, he can create web feeds based on a selected set of tags and
point his feed reader to the given URI to retrieve the matching mails.

3.2 Defining the domain model


Finally, the most important artifact resulting from the analysis is the domain model. It is a rather conceptual
model that is the basis of other more concrete models created during the design steps. It serves to identify the
main domain entities and their relationships.
While reading the textual requirements, you should look for the most important nouns to identify these entities
and their properties. Note that the required analysis skills are the same as the ones necessary in OOA/D. The
domain model is still an object-oriented artifact that we later derive into resource-oriented artifacts.
In figure 8, we identified seven main entities in our example mail system and illustrated their relationships
using a standard UML class diagram.
!!
!!

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !9
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D

!
Figure 8 Domain model of our mail system

If you are not too familiar with UML, just note that the links with a black diamond indicate a composition while
those with a white diamond indicate aggregation. Composition is a stronger form of association indicating that the
life cycle of the contained class is directly connected to the one of its aggregate.
For example, the Account class is composed of several occurrences of the Contact, Mail and Feed classes. You
can also read the associations the other way around. For example, the Contact class is associated to one and only
one Account and the same is true for Mail and Feed classes.
Now there are interesting links between the Mail class, the Feed class and the Tag one. They have no diamond,
indicating that there is no "part of" relationship, no aggregation or composition. It's a more balanced association
relationship corresponding to the notion of "match" between the set of tags and mails or feeds.
As you can see, there is nothing specific to REST and resource-orientation so far, you can just rely on your
existing analysis and UML knowledge. However, this is a key step for the ROA/D methodology as it allows us to
more easily build our resource model later on and to bind it with a persistent object model.

3.3 Describing system sequences


While the use cases diagrams are useful to identify the actors and list the main usages of the application, they
are not describing precisely the input and output events to the system and the sequence of actions that we
described in text above. This is the role of system sequence diagrams. Figure 9 below details the typical sequence
of actions involved when a user wants to compose and send an email.
The actors interacting are listed at the top of the UML sequence diagram and each one of them has a vertical
axis representing the time. The arrows illustrate the messages exchanged between the system parts (Sending Mail
Server and Receiving Mail Server) and the actors (Mail Client).
As our domain is relatively simple, this analysis task might not seem too compelling, but as the complexity of
the domain grows, you will likely rely on it more often. This is also a good preparation for the interaction design in
the next steps.

!
!
Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !10
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D

Figure 9 Sequence diagram describing the email sending process

It would be useful to add a textual description of the diagram and the various interactions. Also, additional
sequence diagrams could be defined, for example regarding the use cases of the administrator. We leave that to
you as an exercise.
Once the requirements are analyzed, we can progress to the next step, which consists in designing a concrete
software solution that matches our requirements and our understanding of the problem domain.

4. Designing the solution


Finally after much effort spent specifying what we need to build, then understanding and describing this what, here
comes the solution design step of a ROA/D iteration. In this step we actively take into account the specificities of
the resource-oriented paradigm and think about how to implement the solution. In this section, we present ROA/
D’s design guidelines summarized in figure 10 and show how they can be applied to our example mail system
(interleaving design guidelines with application of these guidelines to our example).
!!

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !11
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D

Figure 10 Summary of main analysis and design tasks in ROA/D

4.1 Defining the logical architecture


Our first design task is to define a coarse-grained architecture of our solution. At this point we just make the
assumption that you chose to develop a RESTful web project using an object-oriented language such as Java.
In figure 11, we propose the preferred logical architecture to use when applying the ROA/D methodology. It
is composed of four layers building on each other as suggested by the pyramidal layout.

Figure 11 – Layers of the ROA/D logical architecture

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !12
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
At the top, we have the UI layer supporting the interactions with users, for example via a web browser or a
programmatic HTTP client. In order to respect REST principles, those user interfaces must use hypermedia in order
to animate the application and change its state. If the user is a human then it should rely on hypertext displayed in
a browser or in a similar environment, letting the user follow hyperlinks and send forms to interact with the
system. If the user is a robot, a programmatic client, then hypermedia still applies and become hyperdata,
supported by languages such as XML, JSON or RDF.
Below the UI layer we introduce the resources layer that is manipulated by transferring representations back
and forth, invoking HTTP methods on the resources. In this layer, typically implemented using a REST framework
such as Restlet, it is essential to respect another REST principle saying that no state related to client interactions
should be maintained, for example in the form of session objects. The responsibilities of this layer are the
identification of resources by URIs, the formatting and parsing of representations of those resources, the routing of
calls or security enforcement.
Now we could attempt to directly persist those resources into a data store, but in many cases it is preferable to
introduce another layer. The objects layer lets you model, more easily and extensively, the complexity of your
domain model and the associated logic. For example, we can define domain specific object methods and have all
the power of object-oriented programming.
Finally, the data layer supports the persistence of the objects layer and indirectly of the resources layer. Various
types of technologies are available, the most popular being the file system and databases (cloud-scale databases
such as Cassandra, relational databases such as MySQL, object databases such as db4o). Of course, an ORM
(Object-Relational Mapping tool such as Hibernate) can be used to automatically persist your object model into a
relational database.
To summarize, each layer builds on top of each other and the lower level layers have no knowledge of layers
above them, favoring separation of concerns and reusability. The highest layers are the most specific to a given
application while the lowest layers are the most generic and thus the most reusable.
Each layer adds its unique features and advantages, relying on the best paradigm for the job at hand. This is
illustrated in figure 12 with another architecture diagram proposing a more topological view, showing the
constitution of a server component in nested layers, interacting with a client component.

Figure 12 - Topology of the ROA/D logical architecture

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !13
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
Here is the architecture that should apply to our email system example:

▪ For the UI layer, we rely on your preferred web browser and on a programmatic client for Android mobiles.
▪ For the resources layer, we use the Restlet Framework
▪ The objects layer is built using POJOs (Plain Old Java Objects) and persisted into the data layer
▪ For the data layer we use in memory persistence for simplicity purpose, but in a more realistic situation, we
would use a proper database technology.

4.2 Deriving the resource model


Now that you have a clearer picture of the target architecture and the main technological choices, it is time to
explain how you derive the initial domain model produced during the requirements analysis step into a resource
model for the resources layer and into an object model for the objects layer. The production of a design object
model from a conceptual domain model is a topic that has been extensively documented in the OOA/D
methodology. We recommend that you consult a dedicated book [1] if you need assistance in this area.
In addition, if you want to manually derive a relational model from our domain model, we also have
methodologies like the IDEF1 standard [123] at hand. Also, ORM tools are capable of generating the relational
model from the object model for you or even the other way around.
The remaining question is the derivation of the resource model from the domain model. This is the
main specificity of our ROA/D methodology as illustrated in figure 13.
!

!
Figure 13 - Deriving the domain model

We also mentioned on the diagram, the concept of Resource-Object Mapping (ROM) which is the equivalent of
ORM but between resources and objects layers. The Restlet Framework greatly simplifies this mapping.
For now, let's detail the tasks to complete in order to derive the domain model into the resource model.

4.3 Identifying and classifying the resources


At this point in the design of your RESTful web API, you should identify the various resources you'll expose and
classify them. Please note that we use interchangeably the terms “class”, “type” and “category” in their most
common sense: a group of things that have similar characteristics.
In general, as a resource can wrap any concept, it is difficult to list all potential types that you can find in
applications. However, you typically find entity resources, corresponding to domain entities in the domain model,
collection resources to manage a set of entity resources and also service resources focusing on processes, like form
submission acceptors or search query processors.

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !14
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
Beside this general typology, the most important question to ask you is what information from your domain
model actually needs to be exposed via the web API, and in which form. For sure, any class of objects of the
domain model that should be publicly accessible should correspond to a class of resources. For a matter of
simplicity the object class and resource class should be given the similar name.
Relations with "n-n" cardinality between two kinds of object (like the “receivers” relation between the Contact
and Mail object classes) are also good candidates to become resource classes. Resources that act as containers of
other resources should produce a collection resource class and an item resource class. For example if an
application’s main role is to manage mail messages, you should have a "Mails" collection resource class and a
"Mail" entity resource class. In addition, public methods of façade domain classes are also candidates to become
service resource classes.
Finally, note that all domain categories of objects don't need to be directly accessible and therefore won't
become resource types but might instead become part of a representation class for a parent resource. Now, let’s go
back to the design of our RESTful email system. Based on our domain model, we easily identify the following list of
resource classes:

▪ Root: top resource of the RESTful mail system


▪ Account: holder of contacts, mails and feeds
▪ Contact: holder of information on a known person
▪ Mail: message exchanged by users via their accounts
▪ Feed: selection of mails based on matching tags

You may have noticed that the Tag class of the domain model isn't part of this list. In fact, we considered that
even though they could be thought as resources, there is not enough interest in our example for them. We instead
handle them using simple text token stored as properties of the related classes: Mail and Feed.
Among this initial list of resource classes, only Root has a single occurrence. For all other ones we need to
introduce collection resources to manage the creation (POST and PUT methods) and the listing (via GET method) of
contained resources. This gives us these additional resource classes:

▪ Accounts: container of account resources


▪ Contacts: container of contact resources in a given account
▪ Mails: container of mail resources in a given account
▪ Feeds: container of feed resources in a given account

When in doubt regarding a potential resource, ask yourself this question: do I need or want this potential
resource to be accessible on the Web, given a public URI?

4.4 Defining the URI space


As you may know, a resource is anything of interest that a server decides to expose and to uniquely identify with a
URI. For instance, when you surf the Web, each web page is a resource. Your browser typically retrieves its
representation by using its URL, which is a kind of URI, along with the GET method. The URL contains enough
information for the network infrastructure to find the computer hosting the resource and to identify the resource on
this computer.

EACH URI IDENTIFIES A PARTICULAR RESOURCE


To adopt this model you must decide what resources your server-side program exposes, and assign each one a
URI. As we saw in the previous section, resources are typically application-level entities you want to expose to
remote clients. For example, if your application provides weather information, you might want to expose a report
about the current weather in Paris at [Link] The current weather in
Chicago could be described at [Link] and so forth. Or maybe you
want to provide finer-grained access to weather information and define separate resources for temperature,
hygrometry and so on. In this case, the current hygrometry in Paris could be identified by http://
[Link]/Paris/hygrometry and consists of just a number.

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !15
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
Maybe just providing weather information for whole cities is not what you want to do, and your application
might use a more precise and global location system, such as the WGS84 (World Geodetic System), which is used
by GPS. In that case, you might decide to create a resource space that associate a weather report to each place on
earth, localized by its coordinates. For instance, the current weather under the Eiffel tower could be at http://
[Link]/48.85834817715778,2.294543981552124.

CRAFTING YOUR URIS


Each resource instance must be uniquely identifiable using a URI. The first thing is to choose the base URI of your
application that we associate to a root resource, for example [Link]
v1/. Note that we appended “v1” to allow us to serve several versions of the same application at the same time in
the future and facilitate the migration from one version to another without breaking existing clients.
HTTP URIs, or URLs to be more precise, support a hierarchical naming system. The hierarchy is denoted by the
presence of a “/” character between two adjacent elements, also called segments. Consequently it encourages you
to organize your resources into a hierarchy, according to your own rules. The URI of each resource class is
generally the concatenation of the base URI of your application with a resource class name and a trailing slash
character (except for leaf resources that can’t have any child resource). Here is the URI for our example Accounts
resource class: "[Link]
Then for each root, you should append to the parent URI, and as you dive deeper inside the hierarchy, you
append a leading slash and the chosen name of the current level. For each child resource class, a constant name
for non-repeating resources or a unique identifier, followed by a trailing slash if children exist. As it would be
cumbersome to list all potential values of the identifier, we instead use URI variables like "{myId}", following the
URI Templates standard [6].
For example, an account resource class has the following URI template: [Link]
accounts/{accountId}. This should be continued recursively for each child resource class, until you reach the
leaves. In figure 14 hereafter, we illustrate our example resource classes, leveraging the UML Class Diagram. We
tried to use a layout that reproduces the URI hierarchy like nested folders and added UML notes as URI hints.
!!
!!
!!
!!
!!
!!
!!
!!
!!
!!
!!
!

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !16
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D

Figure 14 - Example resources hierarchy as an UML class diagram

Choosing URIs for your resources is always an important design task. They are part of the user interface of your
application as end users do see and manipulate them. So let’s assume that URIs identify concepts and make them
user friendly as much as possible.
In our sample mail application, as we are not planning on hosting it with a registered domain name, instead we
use the generic “localhost” domain as the base URI: [Link]
You can note that leaf resources don't have a trailing slash character to reinforce the fact that they don't contain
anything. Again, this is purely a convenience that helps users of your application but it is not an aspect that
determines whether your design is RESTful or not.

URIS IDENTIFY THINGS, NOT ACTIONS


When designing your URIs, keep in mind that they identify things, not actions. The action a client asks a server
to perform is expressed using the HTTP method, and the request URI denotes the primary target of this action. The
presence of verbs in URIs is often a good indicator of a problem in the design of a RESTful web API. If you come up
with URIs that contains verbs in imperative form, you might be trying to encode requested actions inside your
URIs. In such cases, double check your design and make sure you are not bypassing, or reinventing, the HTTP
method system (see section 4.5).
Of course, verbs that are not used to request actions from the server can be perfectly valid URI elements. For
example, in the online English dictionary service provided by Merriam-Webster, the URI for the definition of the
verb “compute” is [Link] There are also cases where verbs in URIs
are fine even if they describe actions to be performed by the server.

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !17
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
THE QUERY IS A FIRST CLASS URI ELEMENT
For example, the result of a Google search for the word “Restlet” has the following URI: [Link]
search?q=Restlet. This is in line with REST and HTTP because this URI, as a whole, still references a thing: the
result of searching for the word “Restlet”. Indeed, things defined as being the result of some action are still things.
This thing is still manipulated using HTTP methods; in this example, you can get its representation using the GET
method. Indeed, this is what your web browser does when you use the Google web site.
On the other hand, the AWS SimpleDB API uses POST methods on URIs such as [Link]
Action=DeleteDomain&DomainName=MyDomain (shorten for brievety) that should have been expressed as
DELETE methods on a URI like [Link]
The Google search example also answers a common question about the status of the query string: is the query
an integral part of the URI and consequently participate in resource identification? The answer is yes as http://
[Link]/search?q=Restlet and [Link] refer to two different
resources, each one being the result of a different search. The query is an integral part of the URI, just like other
path components (“/search”, for example). Still, you can use different URIs to refer to the same resource if needed,
but this is a general ability with URIs, not something related to the usage of the query string in particular.
Therefore, remember that the query is a first class URI element and that two URIs that differ only in the query can
still refer to two different resources.

URIS ALLOW YOUR SYSTEM TO BECOME PART OF THE WEB


In effect, URIs are some kind of pointers. They can be used wherever needed to refer to resources. But they differ
from pointers in traditional programming languages on a key aspect: a pointer in a C program, or a reference to an
object in Java, is meaningful only inside the applications in which it exists.
On the contrary, a URI is meaningful for everyone, for every system. With URIs, pointers break the application
boundaries. Your resources can be referenced by other systems, and you can reference resources provided by
others. Besides, your resources can be accessed and processed by a number of existing tools such as web
browsers, search engines, and so on. Exposing resources identified by URIs allows your system to be part of the
Web, and to enrich it.

4.5 Defining allowed methods


With HTTP, resources are manipulated through a few predefined operations, formally called methods. Each HTTP
request message sent by a client includes the name of a method. HTTP defines the semantic of these methods at
a generic level (see table 1). Your application then specializes the meaning of each method, for each resource or
execution context.
For example, HTTP states that the DELETE method requests that the target resource is deleted from the server.
The exact meaning of such an operation is then determined by each application. For instance, in our email
application, deleting a resource that represents an account could remove this account from the system, including
all related information in the database such as the contained contacts and mails.

USE HTTP METHODS PROPERLY


To benefit fully from REST and HTTP, you must use HTTP methods according to the semantics mandated by HTTP.
For instance, the GET method is for information retrieval: getting the representation of a resource. You must not
use it for expressing other kind of interactions. To characterize methods, HTTP defines two important properties:
“safe” and “idempotent”:

▪ Safe methods are, from the point of view of the client, for pure information retrieval. If they have side
effects, these effects must be such that the client cannot be held accountable for them, as he did not
request them.
▪ Idempotent methods are such that (aside from error or expiration issues) the side effects of multiple
identical requests are the same as a single request. For example, DELETE is idempotent because a sequence
of two or more identical DELETE requests has the same effect on the server as just one DELETE request: in
both cases, the target resource is deleted. Indeed, trying to delete something that has already been deleted
doesn’t change the outcome.

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !18
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
By these definitions, safe methods have the potential to be invoked automatically by some generic code on the
client side (for example, web crawlers make use of this) whereas non-safe methods require explicit triggering by
the end-user or the client-side application programmer and awareness of the possible side effects.
Requests with idempotent methods have the potential to be automatically reemitted by the network
infrastructure when in doubt over correct reception by the server, without fear of unwanted effects caused by
multiple receptions of the request.

Table 1 - The four main HTTP methods and what the client is asking the server to do when using them

Method What the client is asking Type

GET Give me back a representation of the target resource Safe and idempotent

PUT Create or update the target resource with the Non-safe and idempotent
representation I’m sending you in the body of this request

POST Make the target resource process the data I’m sending to Non-safe and non-idempotent
you in the body of this request

DELETE Delete the target resource and its associated state Non-safe and idempotent

! In addition to the four methods described in table D.1, HTTP also define an OPTIONS method to describe the
communication options available on the target resource. In particular, it allows asking a resource for the list of
methods it supports. Indeed, a given resource might not support all the HTTP methods. For example, you might not
want to allow remote clients to DELETE certain resources you expose. HTTP also defines the HEAD and TRACE
methods. You’ll find a complete description of these methods in the HTTP specification.

TIP
You should not regard HTTP as a low-level protocol an application developer hasn’t to bother with. On the
contrary, HTTP is the high-level protocol with which you are going to directly express the interactions with your
applications over the network. REST brings a set of principles that help you make good use of HTTP, and the
Restlet Framework put all of this in motion in your Java programs. So yes, HTTP is your new friend! We advise
you to grab the HTTP specification [3], become familiar with it and keep it at hand. You also help yourself by
reading a good book about HTTP such as “HTTP: The Definitive Guide” [4]. Along with the Restlet documentation,
these are going to be some of your main resources for everything related to web developments.

When possible, try to use the HTTP methods whose semantics are the most precise. In particular, use the POST
method only if other HTTP methods aren’t a good fit. As specified by HTTP, POST has a rather unbounded semantic.
It means: “take the data I’m sending to this target resource and process it”. As such, you can use it for any kind of
operation, because you have a lot of freedom to define what “process it” means in the context of your application.
But if an operation you want to expose on one of your resources fits the more specific semantics of GET, PUT,
DELETE or another HTTP method, you should use this method instead. At run time the HTTP infrastructure
(composed of the HTTP clients, caches and intermediary proxies) has more information about what the remote
client is actually doing with your resources, and can better handle the situation. For example, it can automatically
resend requests using idempotent methods in case of communication error. It can also cache results of execution of
the GET method, and thus avoid actually sending some requests over the network, which can improve performance
a lot and decrease load on servers.

CONSIDER EACH RESOURCE CLASS


Let’s apply what we just learned to our example. In section 4.4, we defined a complete hierarchy of resource
classes, with associated URI templates. We now need to define for each resource class, what are the allowed
methods. Assuming that we use the HTTP protocol, the common list of methods is generally, GET, POST, PUT,
DELETE and sometimes OPTIONS. In addition, extension methods can also be used in some rare cases such as

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !19
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
WebDAV's MOVE method but be careful at this will limit the accessibility of your web API as many HTTP clients only
support basic HTTP methods.
In order to facilitate the communication of your resource classes design among your team, we recommend
creating detailed UML class diagrams containing sets of related resource classes. In figure 15 below, we refined the
class diagram introduced in figure 13, using an additional compartment below the class name to indicate the
relative URI part, as allowed by UML. We also added the HTTP methods supported.
!

!
Figure 15 - Example resources hierarchy as an UML class diagram describing allowed methods

Note that the Accounts resource class uses a POST method to support the creation of child accounts because we
can’t know in advance the URI of those accounts and therefore can’t use PUT directly to not only update but also
create them.
We leave you as an exercise the creation of a class diagram for the remaining example resources, children of
Account: Contacts, Contact, Mails, Mail, Feeds and Feed.

4.6 Defining response statuses


There is a very important bit of information that is found in every HTTP response message: a status code. Using
this code, your server-side program can communicate crucial information to a client. For instance, the well-known
code 404 means that the resource target has not been found, and consequently, that the server wasn’t able to
further process the request.
HTTP standardizes several important things here:

▪ The way to denote the status code in the response message, along with an associated human readable
“reason phrase”.
▪ The status categories, also called status classes, such “Successful”, “Redirection”, “Server error” and “Client

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !20
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
error”.
▪ A number of predefined status codes, with specified semantics.
▪ A way to create new status codes if needed.
There are codes to signal various errors conditions, action required from the client to complete its interaction
with the server, or other important information about the outcome of the request. You’ll find a few examples below
in table 2.

!
Table 2 - A few examples of common status codes defined by HTTP.

Code Category Name Meaning

200 Successful Success The request has succeeded.

201 Successful Created The request has been fulfilled and resulted in a new
resource being created. The URI of this new resource
should be present in the response message, in the
“Location” header field.

202 Successful Accepted The request has been accepted for processing, but the
processing has not been completed. The response
message should include an indication of the request's
current status and either a pointer to a status monitor or
some estimate of when the client can expect the request to
be fulfilled.

301 Redirection Moved The requested resource has been assigned a new
Permanently permanent URI and any future references to this resource
should use this URI. The new URI should be present in the
response message, in the “Location” header field.

400 Client error Bad Request The request could not be understood by the server due to
malformed syntax. The client should not repeat the request
without modifications.

404 Client error Not Found The server has not found anything matching the request-
target.

405 Client error Method Not The method specified in the Request-Line is not allowed for
Allowed the target resource. The response includes an “Allow”
header containing a list of valid methods for the requested
resource.

500 Server error Internal Server The server encountered an unexpected condition which
Error prevented it from fulfilling the request.

! Having a whole set of status codes already defined and ready to use is very useful. Instead of reinventing the
wheel, you can, and should, use these standardized codes. On the server side, you should strive to return status
codes that accurately describe the outcome of the request. On the client side, you should check the status code of
each response you receive and act accordingly. The HTTP specification gives you information necessary to use
status codes correctly, and the Restlet Framework helps you deal with them easily in Java, including automatically
acting upon some of them (for example, automatically using the redirection information on the client side to reemit
a request if the target resource has moved).

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !21
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
4.7 Defining representation classes
Some HTTP requests or responses contain resource representations. For example, a response to a GET request
typically includes the representation of the target resource. As you may know, a representation is some data
describing the current or intended state of a resource. Obviously, an important task when designing your resource
model is to define the actual format of these representations (for example, an HTML document or an XML
document with a given structure).
Each resource class can have multiple types of representation (for example, HTML can be used when interacting
with web browsers and XML when interacting with purely programmatic clients). These various types of
representation are called representation variants, and are used by a powerful mechanism of HTTP called content
negotiation (see section 4.5 for more on this).
You should design and document the actual structure of each variant. For each variant, you should indicate the
media type, the language, character set and encoding if applicable. For some media types such as XML, it is also
useful to provide an XML Schema. This should be completed by textual descriptions if necessary.
In our example email system, the Root resource is the main entry point for users. It will be accessed by web
browsers, returning a welcome HTML page. When the user tries to access this page for the first time, with a GET
request, an HTTP Basic authentication mechanism will prompt him for a login and password. If the credentials are
valid, the user will be redirected to his account. If the user is an administrator, he instead sees a hyperlink to the
Accounts resource.
The Accounts resource returns an HTML page that contains a list of accessible Account resources. If the
authenticated user is only an owner, he will only see his account. Administrators will see the list of all accounts. In
addition, administrators see an HTML form allowing the creation of new accounts. When a creation is requested, a
POST method is invoked, resulting in a redirection to the created Account. The Accounts resource returns an HTML
page that contains a list of accessible Account resources. Administrators will see the list of all existing accounts. In
addition, administrators see an HTML form allowing the creation of new boxes. Simple owner users can't create
new boxes by themselves; they have to ask to an administrator. The Account resource returns an HTML page with a
form containing the properties (first name, last name, role and nickname). This form can be used to update or
delete the current account. In addition, the HTML page contains hyperlinks to the related Contacts, Mails and Feeds
resources. Also, the resource is able to receive remote mails in XML format via its POST method.
The Contacts resource returns an HTML page that contains a list of Contact resources contained in the parent
MailBox. In addition, an HTML form allows the creation of new contacts. When a creation is requested, a POST
method is invoked, resulting in a redirection to the created Contact. The Contact resource returns an HTML page
with a form containing all the information related to the contact (first name, last name and URI address). This form
can be used to update or delete the current contact.
The Mails resource returns an HTML page that contains a list of Mail resources contained in the parent MailBox.
In addition, an HTML form allows the creation of new mails. When a creation is requested, a POST method is
invoked, resulting in a redirection to the created Mail. The Mail resource returns an HTML page with a form
containing all the information related to the mail (subject, receivers, body text and tags). This form can be used to
update or delete the current mail. This resource is also capable of actually sending the mail to the receivers by
posting it to the receivers' URI address, corresponding to the receivers' account resource.
The Feeds resource returns an HTML page that contains a list of Feed resources contained in the parent
MailBox. In addition, an HTML form allows the creation of new feeds. When a creation is requested, a POST method
is invoked, resulting in a redirection to the created Feed. The Feed resource can return an HTML page to web
browsers with a form containing all the information related to the web feed (name and tags to match) and the list
of matched mails. This form can be used to update or delete the current feed. In addition, this resource can return
an Atom representation for feed readers, leveraging HTTP content negotiation.
The paragraphs above gave you a good description of the behavior of our mail application, especially from a
web browser point of view. It will not be too different for a programmatic client, except that the representation
formats use XML or JSON instead of HTML and web forms. It you want to visually describe this important design
information, you can use UML state chart diagrams which are a natural fit for hypermedia, UML sequence and
activity diagrams.

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !22
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
In figure 16 below, we continued to enrich the previous class diagrams with information related to the
supported representations. We use a special “redirect” keyword to indicate that a redirection is issued, including
the proper status code and the target URI reference to redirect to (communicated as a special “Location” HTTP
header).
!

!
Figure 16 - Example resources hierarchy as an UML class diagram describing representations

Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !23

You might also like