Designing Restful Web Services Part 1 - URIs, Data Format and HTTP Methods

RESTful web services have less rules or standards compared to SOAP and hence a proper design following the best practices and guidelines are very essential for creating good RESTful web services.

If you know http and servlets well, you already know most of the required technologies for implementing RESTful web services. However for developing good RESTful web services, that is not enough.

Understanding REST API designing and gaining the required design skills are more important than learning to code REST web services. 

None of these design guidelines are enforced by any REST APIs including JAX-RS. However following these guidelines will help you to develop good RESTful web services which will be less confusing at both service and client side.

 

Simple steps for designing restful web services

  1. Define the set of URIs representing the entry points to our system

  2. Decide on the data format (e.g. XML, JSON etc.) that will be used to exchange information between services and the client.

  3. Decide on which HTTP methods are allowed by each exposed URI and what these methods do.

  4. Decide on the REST response and error codes. Find out the error scenarios and the http error codes that need to be returned to the client in case of these errors.

 

Designing RESTful URIs

In REST, every resource in your application has an identifiable URI (resource based URI).

Using a unique URI to identify each of your resources (or services), makes each of your resources linkable.

An identifiable URI for every resource is also a basis for the addressability property in resource oriented architecture.

URIs should not be used as substitutes to operations in SOAP web services. Instead, you should use a combination of HTTP methods and data formats to model unique operations in your RESTful system. For example, having URIs like /getEmployee, /deleteEmployee etc. are against the principles of REST, and you should have a URI like /employees and then have the GET and DELETE http methods handle the get and delete operations.

One simple tip to design REST URIs is to see them as static pages categorized into hierarchical folders, and then, use a combination of HTTP methods and data formats to model unique operations. For example, a dynamic uri like /getEmployee?id=1 might be modelled as uri employees/id/1 and combining it with an HTTP get method.

This hierarchical arrangement will also help to denote relationships. For example, /post/{postId}/comments/{commentId} will say that the particular comment is related to this particular message. However, this will require users to know the parent id as well. You may also design them as separate entities.

The RESTful resource URIs usually should contain nouns (e.g. employees, messages etc.) and not verbs (e.g. getEmployee, getMessage etc.). So  look out for nouns or things in your system, as they will represent the resources.

Plural nouns are used to denote collection of resources. You may have a URI like /employees to get a list of all employees.

It would be also nice to provide filtering and pagination and for this purpose you may use query string (e.g. /employees?joinedAfter=2012&offset=11&limit=10).

 

Defining the Data Format

Data formats decide how our data will be represented during exchanges between services and the client.

XML and JSON are two common data formats used with REST web services.

If you are using XML format, you would generally define an XML schema for each representation you want to send.

JSON is also getting more popular as it can be easily parsed using java script at client (browser) side.  

Client and server can set the right headers in an HTTP request/response to tell the other party of the content type sent or expected. A server sets the header ContentType header for this purpose with a value such as application/xml, application/json etc. Client requesting a format is also called content negotiation.

 

Deciding HTTP Methods

We need to decide on which HTTP methods are allowed by each exposed URI and what these methods do. We should not assign any functionality to an HTTP method that is not within the specification defined boundaries for that method. For instance, a safe method like GET should be read only and should not modify anything on server, an idempotent method should not make any irreversible side effects if executed multiple times etc.

We can create a resource on the server by sending a representation of the new resource to the resource URI. Server should return a response code of 201 “Created” if a resource is created successfully on the server. To create a new resource you may either use PUT or POST. PUT is idempotent whereas POST is not. Since creation usually involves generating IDs POST is most preferred.

PUT is preferred for update operation, even though you can use POST as well. According to the HTTP specification, when a resource is updated with PUT, you may either send a response code of 200 “OK” if you are sending back response body or 204 “No Content” if there is no response body.

You may use the DELETE method to delete a resource.

If we have an operation that does not fit into any of the HTTP Methods, we should not try to modify the meaning of the current HTTP methods. One possible way to overcome this situation is to model this operation within the data format. For example, you may include a state parameter (e.g. an xml element or a JSON key/value pair) to denote this extra operation, and can then do a regular PUT (for update). Another way is to have a new resource URI. Second way also allow us to do some filtering using some query parameter and still not violating the uniform interface contract of REST.

 

REST Response

REST is based on HTTP and hence a REST service tells the client about the status of a request using HTTP status codes.

You should try to use the most matching HTTP code as possible:

  • GET/DELETE/PUT send 200 for success and 404 for not found.

  • POST for create send 201 for success.

  • All methods send 500 for failure.

  • DELETE message send also 204 for success.

  • PUT and POST also send 400 (bad request) or 415 (unsupported media type).

 

More Background and Explanations

To know more about the HTTP concepts mentioned in this note including HTTP methods, HTTP error codes and their classification etc., please refer to the note http://javajee.com/introduction-to-http-http-methods-and-http-status-codes.

References and notes: 

http://javajee.com/java-ee-web-components-part1-http-servlets-and-security

RESTful Java with JAX-RS by Bill Burke

RESTful Web Services by Leonard Richardson

Comments

There are some typo mistakes and 'More on REST Response' has some gramatic mistakes.. please correct them.

Was it useful?

thank you for reading and pointing it out.

Was it useful?

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)