You are on page 1of 7

Restful Services

1. REST vs SOAP

RESTful services are services that follow a REST architectural style, as opposed to
SOAP.
- REST -> REpresentational State Transfer – One-way, stateless message passing.
- SOAP -> Simple Object Access Protocol – One-way, stateless message passing.

SOAP:
 Action based
 We use only verbs -> actions we can call getUserData
 An envelope, which defines the message structure[1] and how to process it
 A set of encoding rules for expressing instances of application-defined datatypes
 A convention for representing procedure calls and responses

- 3 constraints or characteristics:
o Extensibility -> e.g. Security and WS-Addressing extensions
o Neutrality -> It can operate over any protocol: HTTP, SMTP, TCP, UDP…
o independence -> It allows for any programming model

REST:
It was part of Roy Fieldings final doctoral dissertation
(https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm)

- It is resource-based, not action based -> In a RESTful Api we talk about things
or resources.
- We use nouns in form of URIs: a person resource (URI), an address resource
(URI), and http verbs for actions or services on those nouns/resources: GET,
POST, PUT, DELETE.
- Multiple URIs can point to the same resource.

- There can be different data representations from the same resource, it is what
is transferred via the clients. It contains enough information to manipulate the
resource (typicaly they use json or xml formats).

Companies tend to switch to RESTful APIs.

1
2. REST six constraints

o Uniform interface

It has a common interface to be used when communicating between client and


server to simplify and decouple the architecture dependencies.
- We use URIs for names/resources.
- We use HTTP verbs for actions on resources.
- We use HTTP responses for representing our resources actions
responses.
o Response status: 200, 400, 500, …
o Response body: { … }

o Stateless(ness)

The service should contain no client state, each message or request should
contain enough information so that the server can know what to do, which
means, if there is a state, it should be at the client side, not at the server side.
- Self descriptive messages
- Any session state is held on the client

Note: OAuth2 is statefull but built in a REST fashion, so there are cases in which
you have to store the state in the server side. But, in general, we should avoid
that. See https://en.wikipedia.org/wiki/OAuth.

o Client-server
That means we are dealing with a disconnected system. This means that it is
possible that we cannot connect or reconnect to our database or to our assets, or
to our services, and we need to handle those cases.
So it helps separating concerns in what is user interface and what are services.
They will communicate via the Uniform interface (nouns and verbs).

o Cacheable
Server responses, anything that comes back from the service
- can be cacheable by the client (implicit caching), or
- the server specifies a maxAge header (explicit caching), or
- client and service negotiate how long the response can be cached
(negotiated caching).

o Layered system
- Relates to cacheability and client-serve
- A RESTful could have multiple layers of software inbetween, so we don’t know
who we are deling with in the server.
- So if a get a representation, I don’t know if it is cached or it comes from the
database, I just get a representation of the resource I need.

2
o Code on Demand (optional)
- From a RESTful server, logic could be transferred as the representation to the
client. E.g. Java applets, executable JavaScript snippets, could be delivered via
RESTful apis.

If you comply with all these first 5 constraints, if you are RESTful compliant, otherwise
you just use the REST interface. If we are RESTful (completely REST), we get the
following benefits:

- Scalability
- Simplicity
- Modifiability
- Visibility
- Portability
- Reliability

3
3. Best practices when defining RESTful URIs

Producing a great API is 80% art and 20% science. Creating a URL hierarchy
representing sensible resources is the art part. Having sensible resource names (which
are just URL paths, such as /customers/12345/orders) improves the clarity of what a
given request does.

Here are some quick-hit rules for URL path (resource name) design:

 Resource names should be nouns. Avoid verbs as resource names, to improve


clarity.

 Use the HTTP methods to specify the verb portion of the request.

 Use identifiers in your URLs instead of in the query-string. Using URL query-
string parameters is fantastic for filtering, but not for resource names.
 Good: /users/12345
 Poor: /api?type=user&id=23

 Use lower-case in URL segments, separating words with underscores ('_') or


hyphens ('-'). Some servers ignore case so it's best to be clear.
 Avoid acronyms, but try to keep URLs as short as possible, with as few
segments as makes sense.

 Avoid using collection verbiage in URLs. For example, 'customer_list' as a


resource. Use pluralization to indicate the collection metaphor.
 Good: /customers
 Bad: /customer-list or /customer_list
 Use plurals for collections in URL segments to keep your API URIs consistent
across all HTTP methods, using the collection metaphor.
 Recommended: /customers/33245/orders/8769/lineitems/1
 Not recommended: /customer/33245/order/8769/lineitem/1

This way, /customers will manage a list of customers and /customers/{id} will
manage a specific customer.

 Leverage the hierarchical nature of the URL to imply structure.


 Design for your clients, not for your data.

4
4. Http verbs

- GET (Readonly)
Read a specific resource (by an identifier) or a collection of resources.
- PUT
Update a specific resource (by an identifier) or a collection of resources. Can also
be used to create a specific resource if the resource identifier is known before-
hand.
- DELETE
Remove/delete a specific resource by an identifier.
- POST
Create a new resource. Also a catch-all verb for operations that don't fit into the
other categories.

5. Http response codes

Suggested usages for the "Top 10" HTTP Response Status Codes are as follows:

- 1xx (Informational): The request was received, continuing process.


- 2xx (Successful): The request was successfully received, understood, and accepted.
- 3xx (Redirection): Further action needs to be taken in order to complete the
request.
- 4xx (Client Error): The request contains bad syntax or cannot be fulfilled.
- 5xx (Server Error): The server failed to fulfill an apparently valid request.

The most important ones are:


2xx (Success), 4xx (Client error) and 5xx (Server Error)

2XX (Success)
- 200 OK – GET, PUT, POST, DELETE
General success status code. This is the most common code. Used to indicate
success.
- 201 CREATED – after PUT or POST (never on GET, DELETE)
Successful creation occurred (via either PUT or POST). Set the Location header to
contain a link to the newly-created resource (on POST). Response body content
may or may not be present.
- 204 NO CONTENT – PUT, DELETE
Indicates success but nothing is in the response body, often used for DELETE and
PUT operations.

5
4XX (Client error)

Errors that the client can be able to solve by their end by changing the values of their
request (headers, body, query parameters, …).

- 400 BAD REQUEST


General error for when fulfilling the request would cause an invalid state. Domain
validation errors, missing data, etc. are some examples.
- 401 UNAUTHORIZED
Error code response for missing or invalid authentication token.
- 403 FORBIDDEN
Error code for when the user is not authorized to perform the operation or the
resource is unavailable for some reason (e.g. time constraints, etc.).
- 404 NOT FOUND
Used when the requested resource is not found, whether it doesn't exist or if
there was a 401 or 403 that, for security reasons, the service wants to mask.
- 405 METHOD NOT ALLOWED
Used to indicate that the requested URL exists, but the requested HTTP method is
not applicable. For example, POST /users/12345 where the API doesn't support
creation of resources this way (with a provided ID). The Allow HTTP header must
be set when returning a 405 to indicate the HTTP methods that are supported. In
the previous case, the header would look like "Allow: GET, PUT, DELETE"
- 409 CONFLICT
Whenever a resource conflict would be caused by fulfilling the request. Duplicate
entries, such as trying to create two customers with the same information, and
deleting root objects when cascade-delete is not supported are a couple of
examples.

5XX (Server error)

Errors that the client cannot be able to solve by their end.

- 500 INTERNAL SERVER ERROR


Never return this intentionally. The general catch-all error when the server-side
throws an exception. Use this only for errors that the consumer cannot address
from their end.

More status codes can be found here:

https://www.restapitutorial.com/httpstatuscodes.html

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

6
HTTP CRUD Specific Item Entire Collection
Verb operations /customers/{id} /customers

GET Read 200 (OK) Single customer. 200 (OK), list of customers. Use
pagination, sorting and filtering to
404 (Not Found) If ID not found or navigate big lists.
invalid.

POST Create 201 (Created), 201 (Created), 'Location' header


with link to /customers/{id}
404 (Not Found) containing new ID.

409 (Conflict) if resource already


exists.

PUT Update/Replace 200 (OK) or 405 (Method Not Allowed), unless


you want to update/replace every
204 (No Content). resource in the entire collection.

404 (Not Found), if ID not found or


invalid.

PATCH Update/Modify 200 (OK) or 405 (Method Not Allowed), unless


you want to modify the collection
(optional) 204 (No Content). itself.

404 (Not Found), if ID not found or


invalid.

DELETE Delete 200 (OK) 405 (Method Not Allowed), unless


you want to delete the whole
404 (Not Found), if ID not found or collection—not often desirable.
invalid.

More info here https://www.restapitutorial.com/lessons/httpmethods.html

CRUD: Create Read Update Delete database operations.

You might also like