Consuming a REST API in Java - java

I need to consume REST API. There are many REST clients for Java. Are there any areas of concerns before proceeding this?

You can use HttpClient for that. However, if you are working on a spring enabled project, I would recommend using RestTemplate.
Rest template provides an abstraction over HTTP client as a result of which you will not have to deal with serialization/deserialition, error handling, SSL configuration in every part of code where you make a REST call. You will just need to configure those with REST template configuration once and not worry about it. This makes your code clean and easily maintainable in case you wish to change the way your application talks to the back-end restful application in future.

Related

How do I test a REST client?

I have a REST client in Java that is ready to connect to a REST server, send a specific request and get a response back. However, the actual REST server is not available during development time (it is hosted by a 3rd party and only available in the isolated local net of the target machine) and we still want to test connectivity and interaction with the server.
Can you point me to a product or technology that in the first place lets me quickly create a fake REST server (or at least mock it) according to the specification of the REST call parameters? I did some research on the web but haven't had a "yes, this is it!" moment yet.
You can use any rest mocking framework to achieve this. As per my experience
Wiremock is the best framework for RES API Mocking.
http://wiremock.org/
You can use mockwebserver library by square. It's pretty simple to use and do exactly what you attempt to do.
Little usage sample:
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setBody("hello world"));
server.start();
For client testing, I would recommend a tool like SOAP UI or Postman. But for mocking the REST service itself, I would actually recommend just creating some dummy endpoints in your Java web application and using that. At each endpoint you could do something hard code a simple response, in JSON, XML, or whatever would make sense with your service. Then, when you finally come to actual development, you will already have a functioning framework for your REST service. You would just need to fill in the missing pieces.
This makes sense because you are going to need to setup REST support in your Java code anyway, and the amount of effort to just add stubs should be minimal. This approach is also attractive from the point of view that it avoids any potential surprises from switching from a mock REST service to the actual one.

Microserivce Using Spring Boot to Consume SOAP

I need to create a REST service that first consumes SOAP. What would the best way to go about this?
I would like to use Spring Boot to create a microservice, but I have a few questions for those with experience:
What other architectures or technologies should I look into using
(with spring boot)?
Is there a standard technology stack for this?
Are there pitfalls I should be aware of?
What other architectures or technologies should I look into using (with spring boot)?
My answer is if you just want to simply provide RESTful service
without Spring Cloud, then I think you can refer to following 2
tutorials on Spring official website to achieve this:
Building a RESTful Web Service
Consuming a SOAP web service
Is there a standard technology stack for this?
Currently, I will suggest you to use Spring Boot as your first choice. Because these are rich resources on the web and it does reduces much effort in development.
Are there pitfalls I should be aware of?
If you finally choose Spring Boot, please be familiar to its components, you can start from Guides to realize how it works. Or you may mix up Spring Boot with tradition Spring framework.
There are similar cases in our project and we did it with spring components. As far as i understood, you want to open a REST endpoint which most probably accepts json object and you want to make a soap web service request within that request then you want to return a response containing information from the soap response. To make a soap request, you can use spring web services - WebServiceTemplate. It will marshall your object to xml and make soap request for you. Of course you can use some other web service frameworks like apache cxf which may best fit for some special cases, but i would first try to use a framework which is from spring family while using Spring. You should set timeout values on webservicetemplate object to not wait too long if the external system is not working well or you have some problems with the network. Because it directly affects your systems performance. Also here, i suggest you to implement circuit breaker pattern to make your system more robust. You should always isolate your systems performance from other systems that you integrate and in this scenario you can do this by doing the things explained above.
As per my knowledge , you should use Spring boot application with Maven build.
In order to send a REST call to SOAP web service and get back a JSON Response ,you need to follow all of this steps in order :
Business Logic : Mapping the JSON fields such as headers, query-param , body variables to XML Request mandatory fields (either using pojo classes or object-mapper) Reason : Since the SOAP end point will only accept XML Request.
Service Broker Logic : Import "org.springframework.web.client.RestTemplate" and use
**ResponseEntity<String> responseEntity=RestTemplate.exchange(endPointURL, HttpMethod.GET/POST/PUT/DELETE, HttpEntity/headers, uriVariables)**
**endpointURL** -- SOAP End point URL ,that the REST service has to consume.
**HTTPMethod** -- Method Type such as GET ,PUT ,POST ,DELETE etc.
**HTTPEntity** -- Soap requires for mandatory sender/headers/{a}.Make sure that you set your header name and value as key-Valye pair in HTTP headers.
**uriVariables** -- (Object... urivariables) such as String.class ,Integer.class
You should also put the **connectTimeout** ,**isSSLDisabled**,**responseCached** elements while generating request to restTemplate.
responseEntity.getBody() is the XML response after un-marshalling.It can be extracted by using mapper.
XML_BaseResponse response=mapper.readValue(responseEntity.getBody(), XML_BaseResponse.class);
Business Logic : Extract necessary field from XML_BaseResponse and using setter's or getter's functions,set the mandatory fields in the response.
baseResponse.setName(xml_baseResponse.getPersonsName());
baseResponse.setAddress(xml_baseResponse.getAddress());
baseResponse.setCity(xml_baseResponse.getcityName());

Which is best/performance putting wrapper top of SOAP service or creating new REST full service?

All services are running in SOAP. for now they client asking us to provide a REST service.
I have two options
Write a wrapper for existing SOAP services to provide REST full services
Brand new REST full service.
Which is better (in performance perspective)?
A single service usually has better performance than a service and a proxy (wrapper).
However SOAP and REST (with JSON) services are approximately equal in performance, you'll come to see that in parsing/serializing XML and JSON to objects representations (with jackson or JAXB), the object creation is the most demanding part, not reading JSON or XML format. The overall impact on performance is probably lower than 5 percent - a single core can usually top 50 mb/s in parse/serialize capacity.
The above also implies that if you already have a very optimized SOAP backend, probably going with the proxy is the right choice.
Moving from SOAP to REST you should use a tool like swagger (OpenAPI) to define the service in as much detail as the SOAP service. Note that REST services also can use XML, but probably that is not what your client is expecting.
Definitely Writing a new Rest web service would be the better choice because
Rest is light weight due to statelesness(due to HTTP protocol).No state is maintained.hence keep ur resources free.
You don't require a schema as you need for soap webservice.Thus serializing and deserializing is also not required.Thus makes performance far better
Testing a rest service would be easy for you.
Even rest is supported to develop an App on the based of REST API you have developed if u require in future.
Rest supports multiple data excahnge formats for ex : json,text etc.
Rest can be easily integrated with high-end frameworks like Spring etc.
You may use better documentation for your service via Swagger for Rest to keep knowledge about your service for business understanding.

Implementing an HTTP proxy to overcome cross-site AJAX requests restrictions (?)

I have a Spring-MVC webapp (3.0.5-RELEASE) which needs to access JSON webservices from another webapp on a different sub-domain (from the client/browser via AJAX).
I've solved this in the past by either:
writing a simple controller that proxies the requests, using Apache Commons HttpClient to handle the requests. Thus overcoming the cross-site/cross-origin request security limitations of most browsers
implementing a JSONP service on the server side (when calling our own JSON services) - not always possible
In the case where JSONP is not possible, is there a better way of doing (1.)?
and/or
Is there a library that will handle this for me? So I don't have to write all the HttpClient code myself - its not a lot of code, but I wonder if I'm (badly) re-inventing the wheel.
I have often had to consume third party web services (API), and as you mentioned, JSONP is not always an option. This is how I go about designing:
If the API is user centric, it has to provide a jsonp interface and that's what I will use. User centric means that you cannot perceive any reason to call the API, do some computations with the response, may be call one of your ajax services and then combine the response and show the user.
If my use case includes calling the API, and then acting on the response, like calling additional services from my application, combining the data and then showing it to the user, I would prefer not doing this in the browser. I would instead use RestTemplate and make backend api calls to the service. In which case there are no cross domain restrictions.
The only case where using a Server Proxy to bypass jsonp is when you are creating a Product that allows people to build custom plugins, plugins which are hosted on your page, but need to make Ajax calls to the app developers servers. This is a very involved case! (As as example look at how Apigee creates Public Facing REST API around your existing urls, or how Zendesk allows you to develop apps)
Hope this helps.

AJAX Using a REST API Without Server Side Framework

I am building a REST based API (Read only) for accessing services of my application. I plan on writing a web application that will leverage these APIs to provide basic information on the status of the application. I plan to use AJAX (using jQuery) to show the information.
Originally I planned on using Grails, Spring MVC, RoR or one of the web frameworks to handle the back end of my application. The REST APIs I will be providing though are already built on a stanalone REST framework so I would only be leveraging the web framework for the core application and not the business logic. In the future, I might need the server side framework to handle other tasks but for now most of the work is done in the REST APIs.
My question is, should I bother with using a web application framework on the server side? I should be able to make all the API calls I need from AJAX directly from the browser. I cannot think of much I would need to do on the server side. Would it make sense to have the application be standard HTML + AJAX + REST?
Its hard to say without actually knowing more about your current setup. This is what your situation sounds like:
You already have an app ready to go with all of the business logic contained. Sounds like its written in Java?
You already have the services written and exposed through a REST api using some other standalone framework. Meaning that if you wanted to, you could access the data right now with the browser without any extra work.
You have not yet built the web application, but when you do, it will get all of its content from the REST api using XHR and jquery. I say that, because otherwise, I would think that you would already be using some kind of framework to generate the other content.
If I am correct in my assumptions, then I would say that you have no need for an additional framework layer. Grails, RoR, SpringMVC my use ajax, and aid in exposing REST services, but the bulk of what they provide is an easy way to make an application that must generate html on the server, deal with form submissions, and handle sessions in a request/response cycle. It doesn't really sound like you'll be doing any of that, and it will likely make your app more complicated.
If you did at some point need the things that rails etc. provides, I would say that you may not need to use rails to expose the rest apis you have now. You could use rails just for what you need, and continue to use what you have for the REST api.
Well, the AJAX calls need to pull data from a server somewhere. If the goal is to avoid a complicated setup on the server side, CherryPy can keep the server side code VERY small.
I've written a simple exapmle below. The first class would be where you put the logic for your ReST API. The code below the class is all you need to get the server up and running.
Install Python 2.6, save the code below to restExample.py. Then in your command line run the python file by doing "python restExample.py". Point your browser to http://localhost:8080/blog/999 and see some JSON come back.
import cherrypy
import json
# Create the controller
class Blog_Controller(object):
def get(self, entryID):
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'title':'Entry Title from DB', 'entry_text': 'Text From DB'})
def update(self, entryID, titleFromPOSTFormInput, textFromPOSTFormInput):
# Update DB with passed in arguments. entryID comes from URL,
# other two entries come from POST
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'success':True})
# Setup URL routes
d = cherrypy.dispatch.RoutesDispatcher()
d.connect(name='blog_entry', route='blog/:entryID', action='get',
controller=Blog_Controller(),
conditions={'method': ['GET']})
d.connect(name='blog_entry', route='blog/update/:entryID', action='update',
controller=Blog_Controller(),
conditions={'method': ['POST']})
config = { '/' : { 'request.dispatch': d } }
cherrypy.tree.mount(root=None, config=config)
# Start the webserver
engine = cherrypy.engine
try:
engine.start()
except:
sys.exit(1)
else:
engine.block()
It sounds like this might be a good use case for GWT with Restlet.
Forgive me for tooting my own horn, but if you are doing AJAX REST stuff with jQuery, you should probably check out my JSON-REST plugin:
http://plugins.jquery.com/project/rest
If you are getting XML back, then this won't be as useful, but you may still be able to adapt some of the code to your needs.

Categories