I am trying to call 3rd party rest api using rest template in aws lambda but connection timeout is happening. this third party api is working fine in postman. Below is the code snippet
@Override
public APIGatewayProxyResponseEvent apply(APIGatewayProxyRequestEvent request) {
Gson gson = new Gson();
EmailRequest emailRequest = gson.fromJson(request.getBody(),EmailRequest.class);
System.out.println("Inside function");
APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
if(emailRequest!=null && emailRequest.getUserId() !=null && emailRequest.getPid()!=null) {
Optional<UserDetail> userDetail = userRepository.findById(emailRequest.getUserId());
Optional<Prospect> prospect = prospectRepository.findById(emailRequest.getPid());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<Prospect> entity = new HttpEntity<>(prospect.get(), httpHeaders);
try {
ResponseEntity<String> result = restTemplate.postForEntity(userDetail.get().getCrmUrl(), entity, String.class);
if(result.getStatusCode().is5xxServerError()) {
responseEvent.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
responseEvent.withBody("Issue while sending email details");
}
responseEvent.setStatusCode(HttpStatus.OK.value());
} catch (ResourceAccessException e) {
responseEvent.setStatusCode(HttpStatus.GATEWAY_TIMEOUT.value());
responseEvent.withBody("Rest templete time out");
return responseEvent;
}
responseEvent.setStatusCode(HttpStatus.OK.value());
responseEvent.withBody("UserId crm : " + userDetail.get().getCrmUrl() +" and Prospect first name : " + prospect.get().getFirstName());
} else {
responseEvent.setStatusCode(HttpStatus.BAD_REQUEST.value());
responseEvent.withBody("Please check the request data");
}
return responseEvent;
}
Please help me out how can I access third party rest api in aws lambda.
This could be due to the fact that a lambda function in a VPC does not have access to the internet by default. From docs:
When you connect a function to a VPC in your account, the function can't access the internet unless your VPC provides access.
A popular way to overcome this is through NAT gateway and private subnet as described in: