Introduction to Rest with Examples – Part 2


In the previous post, we talked about what is REST APIs and discussed a few examples, we particularly, used CURL for our requests. So far, we have established that a request is composed of four parts: endpoint, method, header, and data. We have already explained endpoint and method, now let’s go over the header, data, and some more relevant information on the subject.

Headers

Headers offer information to the server and the client. They are used for a wide range of use cases, such as offering a peek into the body content or for authentication. Typically, HTTP headers follow the property-value pair format; a colon separates them. For instance, the following example consists of a header which informs the server about expecting JSON-based content.

“Content-Type: application/json”. Missing the opening”

By using cURL (we talked about it in the last post), you can use the –header option for sending the HTTP headers. For instance, if you want to send the above-mentioned header, then for the Github API, you can write the following.

curl -H “Content-Type: application/json” https://api.github.com

In order to check all of your sent headers, you can use the –verbose or the –v option at the end of the request. Consider the following command as an example.

Keep in mind that in your result, “*” indicates cURL’s additional information, “<” indicates the response headers and “>” indicates the request headers.

The Data (Body)

Let’s come to the final component of a request, also known as the message or the body. It entails information that is to be sent to any server. To use cURL for sending data, you can use the –data or the –d options like the following format.

For multiple fields, you can write the following .i.e. add two –d options.

It is also possible to break requests into several lines for better readability. When you learn how to spin (start) servers, you can easily create your API and test it with any data. If you are not interested in spinning up a server, you can use Requestbin.com and hit the “create endpoint”. In response, you can get a request which can be used for testing requests. In order to test requests, you have to generate your own request bin. Keep in mind that these request bins have a lifespan of 48 hours. Now you can transfer data to your request bin by using the following.

curl -X POST https://requestb.in/1ix963n1 \

-d name=adam \

-d age=28

cURL’s data transfer is similar to a web page’s form fields. For JSON data, you can alter your “Content-Type” and change it to “application/json”, like this.

curl -X POST https://requestb.in/1ix963n1 \

-H “Content-Type: application/json” \

-d ‘{

“adam”:”value”

“age”:”28”

}’

And with this, your request’s anatomy is finished.

Authentication

While using POST requests with your Github API, a message displays “Requires authentication”. What does this mean exactly?

Developers ensure that there are certain authorization measures so specific actions are only performed by the right parties; this negates the possibilities of impersonation by any malicious third party. PUT, PATCH, DELETE, and POST requests change the database, forcing the developers to design some sort of authentication mechanism. What about the GET request? It also needs authentication but only in some cases.

In the world of web, authentication is performed in two ways. Firstly, there is the generic user/password authentication—known as the basic authentication. Secondly, authentication is done by a secret token. The second method consists of something known as oAuth—it uses Google, Facebook, and other social media platforms for user authentication. For using the user/password authentication, you have to use the “-u” option like the following.

You can test this authentication yourself. Afterward, the previous “requires authentication” response is changed to “Problems parsing JSON”. The reason behind this is that so far, you have not sent any data. Since it is a POST request, data transfer is a must.

HTTP Error Messages and Status Codes

The above-mentioned messages like “Problems parsing JSON” or “Requires authentication” fall into the category of HTTP error messages. These emerge whenever a request has an issue. With HTTP status codes, you can learn your response status instantly. The range of these codes starts from 100+ and end to 500+.

  • The success of your request is signified by 200+.
  • The redirection of the request to any URL is signified by the 300+.
  • If the client causes an error, then the code is 400+.
  • If the server causes an error, then the code is 500+.

In order to debug a response’s status, you can use the head or verbose options. For instance, if you add “-I” in a POST request and do not mention the username/password details, then it can cause a 401 status code. When your request is flawed—either due to incorrect or missing data, a 400 status code appears.

Versions of APIs

Time and again, developers upgrade their APIs, it is a life-long process. When too many modifications are required, the developers should consider creating a new version. When this occurs, it is possible that your application gets an error; due to the fact that you wrote code with respect to the previous version API while the brand-new API is pointed out by your requests.

In order to perform a request for a certain version of the API, there are two methods. Depending on your API’s structure, you can choose any of them.

  • Use endpoint.
  • Use the request header.

For instance, Twitter follows the first strategy. For instance, a website can follow it in this way:

https://api.abc.com/1.1/account/settings.json

On the other hand, Github takes advantage of the second method. For instance, consider the following where the API version is 4 as mentioned in the request header.

curl https://api.abc.com -H Accept:application/abc.v4+json

 

 

Advertisements

What Is Bean in Spring? What is the Scope and Lifecycle of Bean?


What Is Bean in Spring? What is the Scope and Lifecycle of Bean?

To learn about Java Spring, it is necessary to understand what a bean is. Similarly, learn about the scope and lifecycle of a bean.

What Is a Bean in Spring

In Spring, the Spring IoC container manages objects which powers the entire application. These objects are known as beans. All objects which Spring IoC instantiates assembles, and supervises fall into the category of a bean.

You can create a bean by providing the configuration metadata to your container. A bean has the following properties.

  • class: It is a mandatory attribute and defines the bean class which will be required for the generation of the bean.
  • name: It defines a unique name for the bean identifier. If you are working with configuration metadata which is powered by XML, you can utilize the name or id to define the bean identifier.
  • Scope: It defines the scope for all those objects which are generated through a single bean definition.
  • constructor-arg: It is used for the dependency injection.
  • properties: It is used for the dependency injection.
  • autowiring mode: It is used for the dependency injection.
  • lazy-initialization mode: By using a lazy-initiated bean, you can generate an instance of bean whenever the first request comes as opposed to the bean creation at the startup.
  • initialization method: It is used as a callback when the IoC container defines the mandatory properties of the bean.
  • destruction method: It is a callback which is used when the container which holds the bean is eliminated.

Scope Of Bean

While specifying a bean, you can also define its scope. For instance, you can set a “prototype” attribute for a bean’s scope; this means that the Spring has to generate a new instance of bean whenever it is needed. On a similar note, you can use the “singleton” attribute if you need to return bean instances in accordance with your requirements. In total, there are five bean scopes.

  • singleton: It defines a single bean instance for each Spring IoC container.
  • prototype: It defines a single bean instance with multiple instances for an object.
  • request: It defines an HTTP request for a bean.
  • session: It defines an HTTP session for a bean.
  • global-session: It defines a global HTTP session for a bean.

Singleton

When a bean’s scope is defined as a singleton, then precisely one object instance is generated by the Spring IoC container. The instance is then saved in a cache which is used to store all the beans associated with the singleton scope. Afterward, any reference or request which comes for that bean sends back the cached object. By default, the scope of a bean is always set to a singleton. In case, you only require a single bean instance, configure your scope property and change it to single. For instance, consider the following format.

<!—Using the singleton scope to define a bean –>

<bean id = “…” class = “…” scope = “singleton”>

<!–write the configuration and collaborators of the bean here –>

</bean>

Prototype

When the scope is specified as a prototype, a new bean instance is generated by the Spring IoC container whenever a request is generated for that bean. Therefore, utilize the prototype scope when your beans are stateful while using the singleton when they are stateless. To specify a prototype scope, you can use the following format.

<!—Use the prototype scope to define a bean –>

<bean id = “…” class = “…” scope = “prototype”>

<!– write the configuration and collaborators of the bean here –>

</bean>

Bean Life Cycle

After the instantiation of a bean, it can execute initialization so it changes into a usable state. After the need for a bean is completed and subsequently, it is deleted, there has to be some sort of cleanup. In the post, we would discuss 2 of the most crucial lifecycle callback methods for beans.

To begin with, you can write <bean> and use with destroy-method or init-method parameters. The latter is used to define a method which is called first after the bean’s instantiation. The destroy method is used to define a method which is revoked after the deletion of a bean from the container.

Initialization Callbacks

In the org.springframework.beans.factory.InitializingBean interface, you can use the following method.

void afterPropertiesSet() throws Exception;

Therefore, you can easily use this interface and initialize by using the following format.

public class BeanExampleOne implements InitializingBean {

public void afterPropertiesSet() {

// write the code for initialization

}

}

If you are using configuration data which uses XML, then you utilize the attribute, “init-method”, to define a method name having a signature without any argument.

<bean id = “beanExampleOne” class = “examples.BeanExampleOne” init-method = “init”/>

Consider the following definition for your class.

public class BeanExampleOne {

public void init() {

// write the code for initialization

}

}

Destruction Callbacks

In the org.springframework.beans.factory.DisposableBean interface, you can use the following method.

void destroy() throws Exception;

Therefore, you can easily use this interface and initialize by using the following format.

public class BeanExampleTwo implements DisposableBean {

public void destroy() {

// write the code for destruction

}

}

If you are using configuration data which uses XML, then you utilize the attribute, “destroy-method”, to define a method name having a signature without any argument.

<bean id = “beanExampleTwo” class = “examples.BeanExampleTwo” destroy-method = “destroy”/>

Consider the following definition for your class.

public class BeanExampleTwo {

public void destroy() {

// write code for destruction

}

}

When you are working in a non-website application setup with a Spring IoT container, for instance, in a desktop environment, then you can configure a shutdown for the Java Virtual Machine. This helps to create an efficient shutdown and revokes only the appropriate destroy methods.

It must be noted that the use of Disposable Bean or Initializing Bean callbacks is not recommended as XML configuration allows a greater degree of flexibility for the XML configuration.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Are Microservices the Right Fit For You?


The term Microservices was originally coined in 2011. Since then it has been on the radars of modern development organizations.  In the following years, software architecture has gained traction in various IT circles. According to a survey, the enterprises which used microservices were around 36 percent while 26 percent were thinking to include it in the future.

So, why exactly should you use microservices your company? There has to be something unique and more rewarding in it that can compel you to leave your traditional architecture in favor of it. Consider the following reasons to decide for yourself.

Enhance Resilience

Microservices can help to decouple and decentralize your complete application into multiple services. These services are distinct because they operate independently and are separate from each other. As opposed to the conventional monolithic architecture in which code failure can disrupt one function or service, there are little to no possibilities a single service failure to affect another. Moreover, even if you have to do maintain code for multiple systems, it will not be noted by your users.

More Scalability

In a monolithic architecture, when developers have to scale a single function, they have to tweak and adjust other functions as well. Perhaps, one of the biggest advantages of microservices is the scalability which it brings to the table. Since all the services in microservices architecture are separate, therefore it is possible to scale one service or function without having to worry about scaling up the complete application. You can deploy critical business services on different servers to improve the performance and availability of your application whereas your other services remain unaffected.

Right Tool for the Right Task

Microservices ensure that a single vendor does not make you pigeonholed. It can help you to infuse greater flexibility for your projects so rather than trying to make things work with a single tool, you can instead look up for the right tool which can fit your requirements. Each of your services can use any framework, programming language, technology stack, or ancillary services. Despite this heterogeneousness, they can still communicate and connect easily.

Promotion of Services

In microservices, there is no need to rewrite and adjust the complete codebase if you have to change or incorporate a new feature in your application. This is because microservices are ‘loosely coupled’. Therefore, you only have to modify a single service if it is required. The strategy to code your project in smaller increments can help you to test and deploy them independently. In this way, you can promote your services and application quickly, as soon as you complete one service after another.

Maintenance and Debugging

Microservices can help you to test and debug applications easily. The use of smaller modules via continuously testing and delivery means that you can create applications from bugs and errors, thereby improving the reliability and quality of your projects.

Better ROI

With microservices, your resource optimization is instantly improved. They allow different teams to operate by using independent services. As a result, the time needed to deploy is reduced. Moreover, the time for development is also significantly decreased while you can achieve greater reusability as well for your project. The decoupling of services also means that you do not have to spend much on high-priced machines. You can use the standard x86 machines as well. The efficiency which you get from microservices can minimize the costs of infrastructure along with the downtime.

Continuous Delivery

While working with a monolithic architecture, dedicated teams are needed to code discrete modules like front-end, back-end, database, and other parts of the application. On the other hand, microservices allow project managers to add cross-functional teams in the mix who can manage the application lifecycle through a delivery model which is entirely continuous in nature. When testing, operations, and development teams use a single service at the same time, debugging and testing is quickened and made easier. This strategy can help you to develop, test, and deploy your code ‘continuously’. Moreover, you do not have to write new code, instead, you can write code with the help of the existing libraries.

Considerations before Deciding to Use Microservices

If you have decided to use a microservices-based architecture, then review the following considerations.

The State of Your Business

To begin with, you have to think if your business is big enough that it warrants your IT team to work on complex projects independently. If you are not, then it is better to avoid microservices.

Assess the Deployment of Components

Analyze the components and functions of your software. If there are two or more components which you deploy in your project which are completely separate from each other in terms of business processes and capabilities, then it is a wise option to use microservices.

Decide if Your Team Is Skilled for the Project

The use of microservices allows project managers to use smaller teams for development that are well-skilled in their respective expertise. As a result, it helps to quickly generate new functionalities and release it.

Before you adopt the microservices architecture, you have to make sure that your team members are well positioned to operate with continuous integration and deployment. Similarly, you have to see if they can work in a DevOps culture and are experienced enough to work with microservices. In case, they are not good enough yet, you can focus on creating a group who is able to fulfill your requirements to work with microservices architecture. Alternatively, you can also hire experienced individuals to make up a new team.

Define Realistic Roadmap

Exponential scaling is the key to success. Despite the importance of businesses to be agile, it is not necessary for all businesses to scale. If you feel that complexity cannot help you much, then it is better to avoid a microservices architecture. You have to decide on some realistic goals about how your business is going to operate in the future to decide if the adoption of microservices architecture can reap your benefits.