Skip to main content

consume other REST service from REST service [OR] consume 3rd party URI

[for source service] Tools and Technologies:

Oracle 

Eclipse IDE

Spring Data JPA

Spring BOOT 2.4.8 + REST

Java 8

POSTMAN 

[for consuming other REST service from REST service] Tools and Technologies:

Eclipse IDE

Spring BOOT 2.4.8 + REST

Java 8

POSTMAN 

In real time most of the applications not provide DB details and you need to consume 3rd party URI. Client will give only 3rd party URI but client have may have DB and you need to write REST service and deliver that respective stories/task. If you want consume a service

that 3rd party related service must SERVER UP then only we can consume and if it is SERVER DOWN we can't consume.

       For understanding purpose Here I am creating and running 1 Rest Service and making as SERVER UP. 

visit  https://start.spring.io/

give proper dependencies[WEB, DATA JPA, Oracle Driver] and select java version , maven as your comfort etc...

just click on generate it will download in ZIP format extract it and upload into eclipse.

go to file -->import-->maven(double click / expand)-->select existing maven projects-->next-->

browse-->select your project root  folder. In my case

D:\BLOG\springbootrestdatajpaoracle and then click on empty space in projects:  you will see pom.xml with check mark and just click on finish it will create our project structure and dependencies will download . This project is for creating comedian service. We are going to creating another service for consuming this comedian service. In ream time this comedian service  already deployed in server and we are consuming this comedian service.(In this context We can say 3rd party service).

       We are consuming this comedian service from another service. This concept is known as consume 3rd party URI or consume other service from service.

go to src/main/resources just create file application.yml (new -->other -->general-->file-->file Name hit enter )

and add these configuration:

server:

  port: 8095

spring:

  datasource:

    driver-classname: oracle.jdbc.driver.OracleDriver

    url: jdbc:oracle:thin:@localhost:1521:ORCL

    username: SYSTEM

    password: pass

  jpa:

    show-sql: true

    hibernate:

      ddl-auto: update

    properties:

      hibernate:

        dialect: org.hibernate.dialect.Oracle10gDialect

create layers controller, service, repository, model and create respective classes and interfaces.

write the stuff for all classes and interface.

after clean build just update the project and got to main package just run as java application

you will notice like below; seconds may different.

Started SpringbootrestdatajpaoracleApplication in 41.413 seconds (JVM running for 43.347)

Here is Project Structure [already deployed in SERVER and we are consuming this REST service only]. In other words assume client will give this project related Endpoint.



In order to work in your locally download Here source code and Just select your main folder and go to Maven and update it.

Click Here Download Source code:

springbootrestdatajpaoracle

Later, go to main package just run as java application

you will notice like below; seconds may different.

Started SpringbootrestdatajpaoracleApplication in 41.413 seconds (JVM running for 43.347)

Try to Hit service and create some records for inserting records into DB table and also fetch records through endpoint. If it is work then we can consume this endpoint from other REST service. Here is I already done same thing you need to do.😉






😊 Ha-ha pretty Easy right ! Let's consume that REST service from this service.(We are going to creating another service)  

Now again visit https://start.spring.io/ and something whatever we did previously like that we are going to creating new project for consuming other service from service. So We are taking dependency WEB & Maven and Java 8 version. Just Generate project and extract them import it to your ECLIPSE remember 2nd instance you needs to be run.[Open two times eclipse and give workspace different for easy understanding and identifying also give different port number for running project smoothly]

Here is the project structure for consuming other REST service from REST service.


In order to work in your locally download Here source code and Just select your main folder and go to Maven and update it.

Click Here Download Source code:

consume other REST service from REST service


Let's start actual concept:

For running our project:

ConsumeotherservicefromserviceApplication class automatically genearated when ever generating project in spring initializer website into your local Hard disk.

package javaconceptsbyjay.com.youtube;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class ConsumeotherservicefromserviceApplication {


public static void main(String[] args) {

SpringApplication.run(ConsumeotherservicefromserviceApplication.class, args);

}


}

===================================================================

model layer:

Comedian:

 

package javaconceptsbyjay.com.youtube.model;


public class Comedian {

private String comedianName;


private String comedianIndustry;

private double comedianRemuneration;

private int comedianPosition;

public String getComedianName() {

return comedianName;

}

public void setComedianName(String comedianName) {

this.comedianName = comedianName;

}

public String getComedianIndustry() {

return comedianIndustry;

}

public void setComedianIndustry(String comedianIndustry) {

this.comedianIndustry = comedianIndustry;

}

public double getComedianRemuneration() {

return comedianRemuneration;

}

public void setComedianRemuneration(double comedianRemuneration) {

this.comedianRemuneration = comedianRemuneration;

}

public int getComedianPosition() {

return comedianPosition;

}

public void setComedianPosition(int comedianPosition) {

this.comedianPosition = comedianPosition;

}

@Override

public String toString() {

return "Comedian [comedianName=" + comedianName + ", comedianIndustry=" + comedianIndustry

+ ", comedianRemuneration=" + comedianRemuneration + ", comedianPosition=" + comedianPosition + "]";

}

public Comedian(String comedianName, String comedianIndustry, double comedianRemuneration, int comedianPosition) {

super();

this.comedianName = comedianName;

this.comedianIndustry = comedianIndustry;

this.comedianRemuneration = comedianRemuneration;

this.comedianPosition = comedianPosition;

}

public Comedian() {

super();

}

}

================================================================


client layer:

ComedianClient: 

package javaconceptsbyjay.com.youtube.client;


import java.util.List;


import javaconceptsbyjay.com.youtube.model.Comedian;


public interface ComedianClient {


public List<Comedian> comedian();

public String createComedian(Comedian comedian);

}




ComedianClientImpl:


package javaconceptsbyjay.com.youtube.client;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javaconceptsbyjay.com.youtube.model.Comedian;

@Component
public class ComedianClientImpl implements ComedianClient {

private RestTemplate restTemplate;
     
String urlFetchAllComedians="http://localhost:8095/rest/api/comedians/fetchAllComedians";
String createComedian = "http://localhost:8095/rest/api/comedians/createComedian";
@Autowired
public ComedianClientImpl(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}

@Override
public List<Comedian> comedian() {
// TODO Auto-generated method stub
Comedian comedian = new Comedian();
HttpEntity<Comedian> httpEntity = new HttpEntity<Comedian>(comedian);
return restTemplate.exchange(urlFetchAllComedians, HttpMethod.GET, httpEntity, List.class).getBody();
}

@Override
public String createComedian(Comedian comedian) {
HttpEntity<Comedian> httpEntity = new HttpEntity<Comedian>(comedian);
// TODO Auto-generated method stub
return restTemplate.exchange(createComedian, HttpMethod.POST, httpEntity, String.class).getBody();
}

}


Explanation: In order to consuming other REST service from REST service you need to create constructor of client class and pass RestTemplateBuilder and its reference. Using its reference we can call build() method assign to restTemplate by calling this keyword. We already created in the form of Object like 
private RestTemplate restTemplate observe in the program.
RestTemplateBuilder will provide calling capabilities for restTemplate like exchange() method. In the Exchange method we need to pass 3rd party URI/URL, method type means GET or POST or PUT.. etc., httpEntity , Type String or List type or etc., after that we are getting respective Body with getBody() method.
We are creating object for HttpEntity  and in <> symobol we are passing respective type i.e.,Comedian also in the HttpEntity Body ()symbol type reference i.e., comedian we are giving inside this(comedian)symbol.When ever creating object for ComedianClientImpl
RestTemplateBuilder will invoked.



================================================================

service layer:

ComedianService 

package javaconceptsbyjay.com.youtube.service;


import java.util.List;


import javaconceptsbyjay.com.youtube.model.Comedian;


public interface ComedianService {


public List<Comedian> comedianListData();


public String createComedian(Comedian comedian);


}


ComedianServiceImpl:

 

package javaconceptsbyjay.com.youtube.service;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


import javaconceptsbyjay.com.youtube.client.ComedianClient;

import javaconceptsbyjay.com.youtube.model.Comedian;


@Service

public class ComedianServiceImpl implements ComedianService{

@Autowired

private ComedianClient ComedianClient;


@Override

public List<Comedian> comedianListData() {

// TODO Auto-generated method stub

return ComedianClient.comedian();

}


@Override

public String createComedian(Comedian comedian) {

// TODO Auto-generated method stub

return ComedianClient.createComedian(comedian);

}

}


==================================================================

controller layer:

ComedianController :

package javaconceptsbyjay.com.youtube.controller;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javaconceptsbyjay.com.youtube.model.Comedian;
import javaconceptsbyjay.com.youtube.service.ComedianService;

@RestController
@RequestMapping("rest/api/consume/comedianService")
public class ComedianController {

@Autowired
private ComedianService comedianService;

@GetMapping(value="/getAllComedian",produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getAllComedian() {
ResponseEntity responseEntity = null;

List<Comedian> comedianServiceData = comedianService.comedianListData();
if (comedianServiceData == null && comedianServiceData.isEmpty()) {
String message = "No Data Found";
responseEntity = new ResponseEntity<String>(message, HttpStatus.OK);

} else {
responseEntity = new ResponseEntity<List<Comedian>>(comedianServiceData, HttpStatus.OK);
}
return responseEntity;

}

@PostMapping("/createComedian")
public ResponseEntity<String> createComedian(@RequestBody Comedian comedian) {
ResponseEntity responseEntity = null;

try {
String string = comedianService.createComedian(comedian);
responseEntity = new ResponseEntity<String>(string,HttpStatus.OK);
} catch (Exception e) {
responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}

return responseEntity;

}

}
=========================================================

application.properties

server.port=8091

===================================================================

😊 Just run this project you are able to see like this !


Go to postman and hit the endpoint.

consumed 3rd party URI and inserting records (creatting records). Method type is POST.




consumed 3rd party URI and fetching records .Method type GET request.



Oracle DB table:





That's All😇. We written service consume other REST service from REST service we can also say consume 3rd party URI.

I already mentioned in this article just download it into locally play with those projects. 

Also visit my channel from Here(open in new tab):

Java concepts by Jay tutorial 

This article copy righted to https://javacodebypj.blogspot.com/  [OR] https://www.youtube.com/c/JavaconceptsbyJaytutorial 

and Prohibited to other websites.

                                                                     A

                                                        PONNAM  JAY

                                                                 Article








Comments