Designing RESTful Web APIs with ROA/D
Designing RESTful Web APIs with 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!
!
Introduction &
In this document you will learn:
!
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.
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:
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.
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.
3. Mails can have the following statuses: draft, sending, sent, receiving or received
[Link] can have two roles: application administrator and account owner
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] owners can create web feeds tracking the latest mails with a given set of tags
[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
!
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.
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.
!
!
Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !10
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
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.
Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !11
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
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.
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.
!
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.
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:
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:
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?
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.
Restlet Inc. 825 San Antonio Road, Suite 101 | Palo Alto, CA 94303 | USA | [Link] !16
Restlet&Framework&&Designing'a'RESTful'web'API'''''''''''''''''''''''''''''''''''''''''''ROA/D
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.
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.
▪ 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
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.
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.
▪ 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.
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