Can 200 status code be response for POST request

I had assumed that POST should return 201 in case of success. But I have to call API with request body (something like GET + body), which is not supported and I'm going ahead with POST.

I had assumed that POST should return 201 in case of success. But I have to call API with request body (something like GET + body), which is not supported and I'm going ahead with POST.

Since i fetch result(i. e list) when i hit API. Is it ok to return 200 as response , as 201 will be invalid since i'm not creating any new entry.

What is REST API? – The Complete Guide to RESTful APIs

What is REST API? – The Complete Guide to RESTful APIs

We have been using different applications and web pages to get data for various resources. However, have you ever thought, where does this data come from? . So in this article on What is REST API, let us look into how a client communicates with the servers to extract the required information.

The following topics will be covered in this article "What is REST API":

  • Need of REST API
  • What is REST API?
  • Principles of REST API
  • Methods of REST API
  • How to create a REST API?

Now, before I define REST API for you, let me take you through an example to make you understand the need of REST API.

Need of REST API

Consider a scenario where you are using the Book My Show app. Now, obviously, this application needs a lot of Input data, as the data present in the application is never static. Either it is movies getting released on a frequent basis, or various cities showing different languages movies at various times of the day. It’s never static which implies to the fact that data is always changing in these applications.

Now, where do you think we get this data from?

Well, this data is received from the Server or most commonly known as a Web-server. So, the client requests the server for the required information, via an API, and then, the server sends a response to the client.

Over here, the response sent to the client is in the form of an HTML Web Page. But, do you think this is an apt response that you would expect when you send a request?

Well, I am assuming the fact that you would say NO. Since, you would prefer the data to be returned in the form of structured format, rather than the complete Web page.

So, for such reasons, the data returned by the server, in response to the request of the client is either in the format of JSON or XML. Both JSON and XML format have a proper hierarchical structure of data.

Now, this sounds quite simple, right?

But, the only issue which is present in this framework till now is that you have to use a lot of methods to get the required information. To the fact, using these methods to retrieve information, becomes quite cumbersome when you require complex data.

So, this is where REST API comes into the picture. The REST API creates an object, and thereafter send the values of an object in response to the client.

Now, that you know the need of REST, next in this article, let us look into the What is REST API?

What is REST API?

REST suggests to create an object of the data requested by the client and send the values of the object in response to the user. For example, if the user is requesting for a movie in Bangalore at a certain place and time, then you can create an object on the server side.

So, over here, you have an object and you are sending the state of an object. This is why REST is known as Representational State Transfer.

If I have to define REST, then,  Representational State Transfer a.k.a REST is an architectural style as well as an approach for communications purpose that is often used in various web services development.

The architectural style of REST helps in leveraging the lesser use of bandwidth to make an application more suitable for the internet. It is often regarded as the “language of the internet” and is completely based on the resources.

To understand better, let’s dive a little deeper and see how exactly does a REST API work. Basically, the REST API breaks down a transaction in order to create small modules. Now, each of these modules is used to address a specific part of the transaction. This approach provides more flexibility but requires a lot of effort to be built from the very scratch.

So, now that you know what is REST API, let us next understand the constraints or principles which must be satisfied for an application to be regarded as REST API.

Principles of REST API

Well, there are six ground principles laid down by Dr. Fielding who was the one to define the REST API design in 2000. Below are the six guiding principles of REST:

Stateless

The requests sent from a client to a server will contain all the required information to make the server understand the requests sent from the client. This can be either a part of URL,  query-string parameters, body, or even headers. The URL is used to uniquely identify the resource and the body holds the state of the requesting resource. Once the server processes the request, a response is sent to the client through body, status or headers

Client-Server

The client-server architecture enables a uniform interface and separates clients from the servers. This enhances the portability across multiple platforms as well as the scalability of the server components.

Uniform Interface

To obtain the uniformity throughout the application, REST has the following four interface constraints:

  • Resource identification
  • Resource Manipulation using representations
  • Self-descriptive messages
  • Hypermedia as the engine of application state

Cacheable

In order to provide a better performance, the applications are often made cacheable. This is done by labeling the response from the server as cacheable or non-cacheable either implicitly or explicitly. If the response is defined as cacheable, then the client cache can reuse the response data for equivalent responses in the future.

Layered system

The layered system architecture allows an application to be more stable by limiting component behavior. This type of architecture helps in enhancing the application’s security as components in each layer cannot interact beyond the next immediate layer they are in. Also, it enables load balancing and provides shared caches for promoting scalability.

Code on demand

This is an optional constraint and is used the least. It permits a clients code or applets to be downloaded and to be used within the application. In essence, it simplifies the clients by creating a smart application which doesn’t rely on its own code structure.

Now, that you know the principles behind REST API, next let’s look into the Methods of REST API.

Methods of REST API

All of us working with the technology of the web, do CRUD operations. When I say CRUD operations, I mean that we create a resource, read a resource, update a resource and delete a resource. Now, to do these actions, you can actually use the HTTP methods, which are nothing but the REST API Methods. Refer below.

Now that you know what is a REST API and what all you need to mind in order to deliver an efficient application, let’s dive deeper and see the process of building REST API.

How to create a REST API?

In this practical demonstration, I will be creating a simple CRUD REST application using Node.js. To build this application, you will need to install the following:

  1. Node.js
  2. Express.js
  3. Joi
  4. nodemon (Node Monitor)

For this hands-on, I will be using the WebStorm IDE to write and execute the codes. You can use any IDE or code editor according to your choice. So, let’s get started.

Step 1: Create a project directory, which will consist of all the files present in the project. Then, open commands prompt and navigate to the project directory. Refer below.

Step 2: Now, call npm using the below command. This will initialize the npm modules in your system.

npm init

Once you hit enter, Node.js, will ask you to enter a few details related to the project. These details will basically be the metadata for your project. Refer below.

Here you can define your entry point along with several other information. For this demo, I will be using script.js as an entry point.

It will then, ask you for a confirmation for the data you must have mentioned. Just press on Y to confirm. Refer below.

Step 3: Next, you have yo install Express.js using the below command:

npm i express

Express is a web framework which can be used along with Node.js. This web framework will allow you to create Restful APIs, with the help of helper methods, middle layers to configure your application.

Step 3.1: Similarly, you have to install Joi.

npm i joi

This package allows you to create blueprints for JavaScript objects which store information to ensure validation of key information.

Step 3.2: Finally, install the node monitoring package nodemon, using the below command.

npm i -g nodemon

Nodemon, keeps a watch on all the files with any type of extension present in this folder. Also, with nodemon on the watch, you don’t have to restart the Node.js server each time any changes are made. Nodemon will implicitly detect the changes and restart the server for you.

package.json

{
"name": "restapidemo",
"version": "1.0.0",
"description": "Creation of REST API",
"main": "script.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "sahiti_kappagantula",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"joi": "^14.3.1"
}
}

script.js

const express = require('express'); //Import Express
const Joi = require('joi'); //Import Joi
const app = express(); //Create Express Application on the app variable
app.use(express.json()); //used the json file
 
//Give data to the server
const customers = [
{title: 'George', id: 1},
{title: 'Josh', id: 2},
{title: 'Tyler', id: 3},
{title: 'Alice', id: 4},
{title: 'Candice', id: 5}
]
 
//Read Request Handlers
// Display the Message when the URL consist of '/'
app.get('/', (req, res) => {
res.send('Welcome to Edurekas REST API!');
});
// Display the List Of Customers when URL consists of api customers
app.get('/api/customers', (req,res)=> {
res.send(customers);
});
// Display the Information Of Specific Customer when you mention the id.
app.get('/api/customers/:id', (req, res) => {
const customer = customers.find(c => c.id === parseInt(req.params.id));
//If there is no valid customer ID, then display an error with the following message
if (!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Ooops... Cant find what you are looking for!</h2>');
res.send(customer);
});
 
//CREATE Request Handler
//CREATE New Customer Information
app.post('/api/customers', (req, res)=> {
 
const { error } = validateCustomer(req.body);
if (error){
res.status(400).send(error.details[0].message)
return;
}
//Increment the customer id
const customer = {
id: customers.length + 1,
title: req.body.title
};
customers.push(customer);
res.send(customer);
});
 
//Update Request Handler
// Update Existing Customer Information
app.put('/api/customers/:id', (req, res) => {
const customer = customers.find(c=> c.id === parseInt(req.params.id));
if (!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Not Found!! </h2>');
 
const { error } = validateCustomer(req.body);
if (error){
res.status(400).send(error.details[0].message);
return;
}
 
customer.title = req.body.title;
res.send(customer);
});
 
//Delete Request Handler
// Delete Customer Details
app.delete('/api/customers/:id', (req, res) => {
 
const customer = customers.find( c=> c.id === parseInt(req.params.id));
if(!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;"> Not Found!! </h2>');
 
const index = customers.indexOf(customer);
customers.splice(index,1);
 
res.send(customer);
});
//Validate Information
function validateCustomer(customer) {
const schema = {
title: Joi.string().min(3).required()
};
return Joi.validate(customer, schema);
 
}
 
//PORT ENVIRONMENT VARIABLE
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));

Step 4: Now, the next step is to check whether the handlers are working properly or not. For that, we will use a Chrome extension called Postman. To install Postman you can visit here and click on ‘Add to Chrome’.

Step 5: Now, once you have installed Postman, open it to test your application.

Step 6: But before that you have to start your server. To start your server, type the following command.

node script.js

You would see the output as below:

Results

Let us start by testing the GET Method.

Step 7: In order to do that you need to select GET from the drop-down list, type in the defined URL and hit send.

If your code is working fine, then you will see the list of all the customers which we have added manually in our code. In the below picture, you can see how my result looks like. Here I have mentioned the URL to be localhost:8080/api/customers

Step 8: Now, let’s try adding a new customer to our stack of customers. For that, select ‘POST’ from the drop-down list and type in the defined URL for the POST method. Then, click on ‘Body’, select ‘raw’ and move on to select ‘JSON’ from the drop-down list as depicted in the below image. Now, in the text area, type in the name of your customer as shown and hit send.

If your POST method is working fine, your response body will contain the new customer’s name along with the Customer ID. Here if you observe, we have only mentioned the name but we did not give the customer ID. This implies that the Customer ID is automatically incremented

Step 9: Now, let’s try to update a Customer name. Let us say we ant to update the name of the Customer ID = 3. So, to update the data, you need to first select ‘PUT’ from the drop-down table and enter the PUT request’s URL along with the customer id you wish to update. Next in the ‘Body’, type in the new customer name and hit enter.

This will give you a response with the customer id and updated customer name.

Step 10: Finally, let’s send a ‘DELETE’ request to delete an existing record. For that select DELETE from the drop-down list and type in the URL of the delete request handler along with the customer’s details, you want to remove and hit enter. Let’s say, I want to delete the details of a customer with id = 3. If your transaction is successful, you will see the complete details of the entry you have removed in the response body.

Now, let’s send a GET request for our final list of customers.

As you can see from the above screenshot, the response body contains a total of five customers with the customer id 3 missing as we have already deleted that entry.





What is REST API? | Restful Web Service

What is REST API? | Restful Web Service

In this post "Restful Web Service", you'll learn: What is Web services, what is API, What is REST API, How REST works and Implementation of REST API

What is REST API? | Restful Web Service

A REST API defines a set of functions to process requests and responses via HTTP protocol.

REST is used in mobile application as well as in web applications.


5 Signs That Your REST API Isn't RESTful

5 Signs That Your REST API Isn't RESTful

This article is for developers who are wishing to implement a RESTful HTTP interface in its original Fieldingian meaning, thereby solving real integration problems that can be addressed only to a lesser extent with today’s colloquial interpretation of the concept.

This article is for developers who are wishing to implement a RESTful HTTP interface in its original Fieldingian meaning, thereby solving real integration problems that can be addressed only to a lesser extent with today’s colloquial interpretation of the concept.

The author provides five criteria to help you make the distinction between an API that is RESTful based on the original meaning versus the colloquial meaning of REST.

There is no doubt that the term REST has undergone significant changes since its inception by Roy Fielding. There was some resistance to this change, most notably from Mr. Fielding in his Untangled Blog. However, all those participating in this resistance have had to acknowledge defeat by now, as the industry has moved past them. We’re using the terms REST and REST API not for its original meaning, but, ironically enough, for (basically) opposing SOAP, an arguably more complex and difficult-to-use contender for integration technology.

Nowadays, everything that communicates over HTTP and uses JSON- or XML-formatted messages or the HTTP Methods (get, post, put, delete, etc.) gets called a RESTful API.

This article is not about discussing whether the term is used correctly, whether certain projects are allowed to use the term, or to argue that the currently implemented APIs are somehow defective.

This article is for developers who are wishing to implement a RESTful HTTP interface in its original Fieldingian meaning, thereby solving real integration problems that can be addressed only to a lesser extent with today’s colloquial interpretation of the concept.

Because the currently available resources (documentation and software) are ambiguous at best, this article offers a simple list of often seen attributes which can help to keep a design on the right track or to differentiate between the original and new interpretation of REST.

1. Using the Application/JSON Media Type

One of the most often seen attributes of API designs is to use the Media Type application/JSON or sometimes application/XML. With Jersey (JAX-RS), it looks often like this:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Product> getProducts() {
   ...
}

Using generic media types such as JSON is fundamentally not RESTful because REST requires the messages to be self-descriptive. Self-descriptiveness just means that the semantics of the data should travel with the data itself.

The difference is similar to the following two options. See which one you would prefer:

Object getProducts();

Or:

List<Product> getProducts();

The first one just says it returns an Object, in which case you have to know what actual type that object is to be able to cast and use it. The second one explicitly states that it is, in fact, a list of products.

By using generic Media Types, you are relying on the client to know what is inside that JSON message and how to interpret it. This is called implicit knowledge and is primarily responsible for brittleness, the tendency for something to break because of changes made elsewhere.

To counteract brittleness, it is best if all messages define their own Media Type, just as all Types in code define their own Class. This definition should not just include syntax but also how to interpret the message, how to follow its links, how to process its forms if there are any, how to display it on screen, and so on.

2. IDs in Representations

Often, representations returned from the server (or sent to the server) contain IDs (Identifiers) in form of numbers, similar to number typed primary keys in a database table. It looks like this:

{ "products": [
  { "id": 12,
    "type": 103,
    "name": "ACME Router D12"
  },
  { "id": 13,
    "type": 145,
    "name": "5m UTP Cable"
  },
  ...
]}

Again, taking an example from Java, which API would you prefer?

List<Long> getProducts();

Or:

List<Product> getProducts();

The first one gives you a list of Identifiers with which you can get a real Product from somewhere. The second one returns the explicit Object references that you can use to operate on those Products directly.

Using numerical IDs is not RESTful for two distinct reasons. First, it requires implicit knowledge from the client to know where and how those IDs can be used to get Products. This again increases brittleness and coupling. Second, it doesn’t use HTTP’s native identifiers (URIs) to identify resources.

The above example should look more like this to be more RESTful:

{ "products": [
  { "id": "/product/12",
    "type": "/type/103",
    "name": "ACME Router D12"
  },
  { "id": "/product/13",
    "type": "/product/145",
    "name": "5m UTP Cable"
  },
  ...
]}

It is not a big change syntactically but it relieves the client of having to know things implicitly.

3. Documentation Is Concerned With Paths and Parameters

Very often, if any documentation is released about an API, it contains a listing of the paths, parameters, fields that are present in the request or response. Some tools like Swagger or WADL are explicitly centered around these concepts. Both the specification and the documentation generated from these tools look like this:

Path: "/products"
  - GET: Get all products
Path: "/product/{id}"
  - GET: Get the product with given id
  - DELETE: Delete the product
...

See the Swagger Petstore for a complete example of this.

This is not RESTful in the original sense because it assumes that the client has to know all these Paths and Parameters, and what they mean implicitly. However, if the Representations use Links and Forms, like in the previous point, none of this information is relevant to the client, since the client then just follows wherever the Representations lead.

What the Specification and Documentation should do, however, is describe all the Media Types that are defined, much like the API Documentation of Java Code. A very minimal example would look like this:

Type: "application/vnd.acme.productlist+json"
  - Represents a paged product listing in the following JSON format:
    { "products": [
      { "self": "/product/123",
        "name": "ACME Router"
      },
      ...
      ],
      "nextPage": "/products?page=3",
      "previousPage": "/products?page=1"
    }
  - The "self" link in Products leads to the product listed
  - The global "nextPage" link, if present, leads to the next page
    of the product listing
  - Similarly, the "previousPage" to the previous (if not on first page)

It specifically does not mention where such a representation might be; it simply describes how to deal with it once received. It also doesn’t mention how to generate the Path to the next or previous pages or how to append Parameters or Path fragments, it simply provides those links already composed for the client to use. It shouldn’t matter how those links are created, and in fact, the server can decide to change such implementation details without notice.

4. URI Templates

URI Templates are URIs with placeholders in them. With the help of named substitution variables, they can be used to generate specific URIs. They look like this:

/product/{id}
/products?page={pageNumber}
/products?startIndex={startIndex}&endIndex={endIndex}
...

These are usually used in specifications or documentations to describe where resources reside and it is expected that clients know these templates and can generate the full URI of a specific resource.

This is done because these resources are not referenced form (linked to) other resources, so the client needs to somehow guess a resource’s URI manually. The problem with this approach is the same as before; this makes the clients break easily if some of the rules change or if the server decides to introduce a different resource structure.

The proper solution to these problems is to link those resources from somewhere else and hide all information about the URI structure from the client. Individual products should be linked from a product listing resource. If the product listing resource is paged, then those pages are again linked. The client does not decide to construct the link for the fifth page; rather, it clicks the nextPage links until it arrives at the desired page. Or, if there is a direct link to the fifth page, it chooses that link to go to that page directly.

There are of course cases in which following links is not enough. What if the client wishes to search for a product? It certainly isn’t feasible (although it should be possible) to follow links until the desired product is reached. These cases are not that different from simply linking the desired resources, however. The server always needs to tell the client how to construct links to follow. It may actually use URI Templates to do this as long as these are communicated in the messages themselves and not out-of-band (in the documentation, for example). A search page might look like this:

{
  "search": "/search?q={query}"
}

The Media Type for this representation has to describe how to interpret the URI Template, how to fill it out, and what the query means so that this knowledge is not implicit anymore. The client then makes the search request based on the information from the search page, not because of some hard-coded rules.

5. Version Number in the URI

A lot of vendors put the version of their API in the URI (for example, Yahoo, Google, Twitter, eBay, and others). This usually looks like:

/api/v1/products
/api/products_v1
/api/products?version=v1
...

From the perspective of the original REST style, these look very suspicious because URIs identify Resources that are supposed to represent some business-relevant concept. These might include Person, Customer, Product, Product Listing, Order, etc. If you ask a business person, “What is a Customer Version 2?” he or she will probably look at you very strangely and wonder whether she will have the opportunity to sell to new, improved customers.

There are practical advantages of URIs that don’t change with a version upgrade, like more flexibility when upgrading individual services, being able to bookmark links to resources without them ever changing, etc.

It is, of course, not the Product or Customer concept that is changing, but the Representation, the format of the message, or the features that it supports. There are multiple ways these changes can be described without violating REST. One of the easiest ones is to just version the Media Types themselves:

application/vnd.acme.product-v1+json

Or, the Media Type definition coulddefine extra parameters for the Media Type identification itself:

application/vnd.acme.product+json; version=1

Or, the Media Type could define that the content itself will somehow indicate the exact version, using the XSD identifier, a JSON field, and so on.

There are certainly more ways to do versioning without changing the URI and staying REST conform. Whatever the mechanism, though, it has to be explicitly defined by the Media Type.

Summary

There are at least two meanings of the word REST in use today:

  • The original meaning in which complex integration problems are solved with rigorous constraints on the architecture.
  • The colloquial meaning in which services publish some form of (often) JSON-based interface through HTTP.

Neither is better or worse than the other in any objective sense. However, if you explicitly want to leverage the full power of the original concept, you probably face the problem of distinguishing which kind of REST some online documentation, article, or software uses.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!