RESTful Web Services : Simple Tutorial for Beginners

If you are familiar with modern web development then you will have encounter the terms like REST and API. If you have worked with APIs or heard of these terms but do not have complete understanding of how to build your own API or how they communicate and work, this tutorial RESTful web services - simple tutorial for beginners is for you.

In this tutorial, I will be sharing what are REST and RESTful APIs, overview of REST principles, understanding the terms Request and Response, REST API Endpoints and at last conclusion.

Read Also : Web Services Interview Questions

Understanding REST and RESTful APIs

REST is an abstract concept. It is not a framework, programming language or kind of software.

REST is also known as Representational State Transfer. It conveys an architectural style for web-services.

REST provides a set of standards or constraints for sharing data between different systems.
RESTful systems are those systems which implement REST.

First we will understand what is an API before understanding the term RESTful API.

An API (Application Programming Interface) is an interface that permit communication between software programs. A RESTful API is an API that follows the standards and constraints of REST.
In a Web API, request is passed to the server through a URL endpoint(see below) and after processing the request, a response is sent. Response is often data in a format like JSON.

Overview of REST Principles

For REST, we have mentioned standards and constraints that need to follow to allow sharing data between different systems. Let look at the 4 guiding constraints:

1. Server-Client :  Separation of concerns between the server (stores and manipulate data) and the client(send request and show response).

2. Stateless : All information needed about each request is put in each individual request and does not depend on session.

3. Uniform interface : Paths that can be entered into the browser's location bar use URI standard to identify resources.

4. Cacheable : Server and client can cache resources.

What is URL, HTTP, Request and Response

If you have browse internet, then you must have come across the fact that all websites have URLs (uniform resource locator) that starts with http or https(secure version).
URL is the address of a world wide web page.

Hyper Text Transfer Protocol (HTTP) is a protocol in other words it allows communication between servers and clients on the internet.

Thinking only HTTP can be used just for requesting websites from servers is not correct. It is more than that.

When you hit a URL on the web, you are really performing a GET request for that particular resource and the webpage shows on the browser is the body of the response. I will discuss about GET and other types of requests in this post later.

HTTP works by starting a TCP(Transmission Control Protocol) connection to a server port (443 for https and 80 for http) to make a request and then waiting for server which responds with a status and a body.

Generally a request must contain URL, a method,a body and header information.

Request Methods (HTTP verbs)

There are four mostly used HTTP methods. These methods are also called as HTTP verbs. These are used to interact with web APIs. These methods define the action to be taken with any given resource.

HTTP request methods loosely follow the paradigm of CRUD (Create, Read, Update, Delete).
Below table will clear the above statement.

Action         Request Method(Http Verb)             

Read            GET                                             

Create          POST                                          

Update         PUT                                            

Delete          DELETE                         


GET request is used only for read operations. It will not change the state of the server. Everytime you are hitting a  URL in your browser such as https://javahungry.blogspot.com or https://google.com , you are sending a GET request to Google's servers (blogspot is also owned by Google).

POST request in RESTful services is used to create a new resource. The most common usage of POST request is to sign up as an User for a website or an app. When you submit the form a POST request with the user data might be sent to the server, which is further upon write that information into a database.

PUT request in RESTful services is used to update an existing resource. The most common usage of PUT request is to edit the profile of an existing user. PUT is idempotent while POST is not.
Idempotent means same result is produced irrespective of the number of times the same call made. In other words, making multiple identical requests produces the same result.

Consider the following example :

 int temp = 8;

 temp++ ;

The first line int temp = 8 is idempotent. temp will always show value 8 irrespective of the number of times you execute the first line.
The second line temp++ is not idempotent. Executing second line 100 times will produce different result then executing it for 10 times.

DELETE request is simply used to delete the existing resource.

Response Codes :

Once a request is triggered from client to the server, the server will return a HTTP response.
A HTTP response contains metadata such as headers as well as the body.
Status code is the most important part of the response, which indicates if a request was successful, if there was an error or if any other action must be taken.

The most common response code you will be knowing is 404, representing Not Found.  4xx class of status codes represents client errors. 404 is a part of it.
Status codes generally categorized into five classes and each class contain a range of responses.

1xx    Information
2xx    Success
3xx    Redirection
4xx    Client errors
5xx    Server errors

Other common responses you may know are 301 Moved Permanently, which is used for redirection, in other words, redirect websites to new URLs.
Another common response is 500 Internal Server Error, this error comes up when something unexpected occurred on a server that makes it impossible to execute the triggered request.

RESTful APIs and their HTTP verbs have all the responses should be in 2xx range.

Request             Response
GET                 200(Success)
POST             201(Created)
PUT                200(Success)
DELETE     200(Success), 202 (Accepted), 204 (No Content)

200 is the response which indicates that a request is successfully processed. It is commonly used as a response for a GET or PUT request.

POST will return a 201 created response to show that a new resource has been created.

DELETE has a few responses which are acceptable. For e.g 202 represents a request has been accepted while 204 request indicates there is no content to return because the resource does not exist.

cURL Requests

Status code of a resource request  can be tested using cURL. cURL is a command-line tool which is used to transfer data through URLs. Using curl, followed by -i or -include flag and followed by URL will send a GET request to the URL. Response sent back from the server will contain the headers and the body.

For example :

curl -include https://www.google.com

Google's server response is following:

HTTP/2 200

date: Mon, 22 Jul 2019 11:59:40 GMT

expires: -1

cache-control: private, max-age=0

content-type: text/html; charset=ISO-8859-1

...


As you can see , the request we sent processed successfully. We got 200 as status code, along with the version of HTTP.(HTTP version can be either HTTP/1.1 or HTTP/2)

Since in this request we are requesting a website(Google.com) , the content-type(MIME type) returned is text/html.
In a RESTful API , the most likely content-type will be application/json to represent the response is JSON.

We can also see different type of response by putting a slightly different URL.
We will execute curl command on Google without www

For example :

curl -i https://google.com


Google's server response is following:

HTTP/2 301

location: https://www.google.com/

content-type: text/html; charset=UTF-8

...


As you can see in the above response Google redirects google.com to www.google.com. 301 status code represents the resource is being redirected.

REST API Endpoints

When you deploy the code on the server, in other words API is created on the server. Then, you can access the data through endpoints.

What is an endpoint?

An endpoint is the URL of the request that can accept and process the POST, GET, DELETE or PUT request.

An API URL will consist of the following parts :

a. root :  for e.g https://example.domain.com/ or https://example.domain.com/v2
In short, root may contain protocol, domain-name and version.

b. path : for e.g https://example.com/books/  or
https://example.com/books/123/   provides unique location for a resource

c. optional query string :  https://example.com/books?limit=10&&type=fiction
optional key-value pairs are used for pagination, sorting and filtering.

In IT industry when engineers say an API is RESTful API, they are pointing to the following naming conventions that put into building the API URL endpoints.

Standard Naming Convention for RESTful API

1. Paths are case sensitive. For example https://example.com/books/3/ is different from https://example.com/Books/3/

2. Paths should be plural for e.g http://example.com/books/5/ is correct. Following is not correct http://example.com/book/5/

3. Path should be written in lowercase using hyphens as opposed to underscores.

4. Endpoints should not show file extensions in the URL.

5. Endpoints should use nouns instead of verbs. In other words, REST URL should not contain words like delete or add.

Above mentioned conventions are only guidelines. There are no strict rules for following REST standards. However, following above conventions make your API easy to read and understand, also consistent.

That's all for the day. If you like the above article on RESTful web services : simple tutorial for beginners or have questions then please mention in comments.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry