Empty response body from GET request in Twilio Messaging API - spring

I'm building a Java Spring application that makes use of Twilio SMS service and it works fine, except that when testing the API with Postman I only get a 200 OK status but a completely empty response body with no JSON at all. I'm not sure if this is a config issue with Postman or with my code, but it's pretty much following the documentation:
#Service
public class SmsService {
#Value("${twilio.sid}")
private String twilioSid;
#Value("${twilio.key}")
private String twilioKey;
#Value("${twilio.phone.from}")
private String twilioPhoneFrom;
#Value("${twilio.phone.to}")
private String twilioPhoneTo;
public void sendSms() {
Twilio.init(twilioSid, twilioKey);
PhoneNumber to = new PhoneNumber(twilioPhoneTo);
PhoneNumber from = new PhoneNumber(twilioPhoneFrom);
String msg = "Some message";
Message message = Message.creator(to, from, msg).create();
System.out.println(message.getSid());
}
}
Here they show a clear example of how it's possible to get a complete JSON response back from HTTP requests.

I also followed that tutorial and it doesn't really return any messages. If you did the entire Bootcamp from DevSuperior, in Java code it just puts an output to the console to confirm that the message was generated successfully.

Related

Testing JsonPatch in Spring Boot application

I'm trying out JsonPatch but ran into an issue when I try to test it. My REST controller looks like this:
#RestController
#RequestMapping("/v1/arbetsorder")
class ArbetsorderController {
#PatchMapping(path ="/tider/{tid-id}", consumes = "application/json-patch+json")
public ResponseEntity<Persontid> patchTid(#PathVariable("tid-id") Long id, #RequestBody JsonPatch patch) {
Persontid modifieradPersontid = personTidService.patchPersontid(id, patch);
return new ResponseEntity<>(modifieradPersontid, HttpStatus.OK);
}
}
I'm testing this endpoint using this method:
#Test
void patchPersontid() {
String body = "{\"op\":\"replace\",\"path\":\"/resursID\",\"value\":\"Jonas\"}";
given()
.auth().basic(user, pwd)
.port(port)
.header(CONTENT_TYPE, "application/json-patch+json")
.body(body)
.when()
.patch("/v1/arbetsorder/tider/3")
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("resursID", equalTo("Jonas"));
}
But this test fails because the status code is 500 instead of 200. I'm not reaching my endpoint.
I have tried using regular JSON and then everything works fine.
Can anyone help me understand why I'm not reaching my endpoint when using JsonPatch?
Apparently the body I send to the endpoint has to be an array in order for it to be converted to a JsonPatch object. Changing my body to:
String body = "[{\"op\":\"replace\",\"path\":\"/resursID\",\"value\":\"Jonas\"}]";
solved my problem!

Mapping dynamic response to Java Object in RestTemplate

I've used RestTemplate to consume remote REST API and I'm getting two different responses for the same request depend on data availability.
eg:- Valid Response
User {
username,
password
}
Error Response when user not found in records.
Error {
errorCode,
errorMessage
}
And this User response has mapped using restTemplate.getForEntity("url", User.class).
Additionally handled RestTemplate Errors using ResponseErrorHandler,
Is there any way to capture both User response and Error Response using resttemplate in same time?
I usually include both/all option and ignore null values, below example
#JsonInclude(Include.NON_NULL)
public class ResponseVO {
private User user;
private Error error;
}
If all data in same level, you can add all members in same class

Spring Boot Tries to Access A Post Request URL but shows GET not supported

I just started to learn Spring Boot today, and I wanted to create a GET/POST request for my Spring Boot Project. When I tried to access the URL that has the post request it shows 405 error saying that "Request method 'GET' not supported".
I think it is something wrong about my code for the POST request, but I don't know where I did wrong. I tried to search for the a tutorial that teaches how to write a proper GET/POST request, so I couldn't find anything good.
If you guys have any good website that teaches basic HTTP requests in Spring Boot, that will be great. I tried to find answers at StackOverflow, but I didn't find anything answers.
The Spring Boot project I have been using is the one from the official Spring.io website: https://spring.io/guides/gs/rest-service/
I wanted to call the POST request for my project so I have a better understanding of the HTTP.
Here is the source code for the controller:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
// GET Request
#RequestMapping(value="/greeting", method = GET)
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(), name);
}
#RequestMapping(value = "/testpost", method = RequestMethod.POST)
public String testpost() {
return "ok";
}
}
Here is the source code for the Application:
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And here is the source code for the Greeting Object
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
I can get the GET request working by using the "/greeting" URL.
I tried to access the "/testpost" url but it shows 405 error that the GET method is not supported.
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
If you try to open the http://localhost:8080/testpost by directly opening in browser, it won't work because opening in browser makes a GET request.
I am not sure how you are trying to do a post request, I tried to do the same post request from postman and able to get the response. Below is the screenshot.
It looks like you are trying to make post request directly from web browser which will not work.
When you hit a URL directly from web browser address bar, it is considered as GET request. Since in your case, there is no GET API as /testpost , it is giving error.
Try to use rest client such as Postman or curl command to make post request.
I tried your post end-point with postman and it is working properly. PFA snapshot for your reference.
Hope this helps.
From where you are trying POST request. If from browser windows you calling POST call, then it will not work, browser will send only GET request. Have you tried from postman or from UI side. It will work.

Error Handling in REST API: Best Practice

I am trying to develop a rest api that basically return information about country. So my url will be something like
http://myrestservice/country/US
so when a request come with valid country, my rest service will prepare information for that country and prepare object called countryInfo and return this as
return ResponseEntity.status(200).body(countryInfo);
now say user send request as
http://myrestservice/country/XX. In this case since XX is not valid country i have send response. I read in different place and most of them only explain about status code. My question is what is the best way to return error.
return ResponseEntity.status(404).body("Invalid Country");
return ResponseEntity.status(404).body(myobject); //here myObject will be null.
Prepare a Class say MyResponse.java as below.
public class MyResponse {
private String errorCode;
private String errorDescription;
private CountryInfo countryInfo
}
And return this object no matter if there are error or not. If there is error set errorCode and errorDescription field with proper value and set countryInfo to null and for no error set errorCode and errorDescription as empty and countryInfo with data.
Which of the above option is considered standard way to handle error.
You should indeed return a 404, but what you return in the body depends on you.
Some people just return a html response with some human-readable information, but if you want your API client to get some more information about why the 404 happened, you might also want to return JSON.
Instead of using your own format, you should use the standard application/problem+json. It's a very simple format:
https://www.rfc-editor.org/rfc/rfc7807
You could use #ControllerAdvice to handle exceptions:
Your endpoint needs to identify the error and throw an error:
#RequestMapping("/country/{code}")
public ResponseEntity<Country> findCountry(String code) {
Country country = this.countryRepository(code);
if(country == null) throws new IllegalArgumentException("Invalid country code: " + code);
return ResponseEntity.status(200).body(country);
}
Then you create a class that will handle the exceptions of your endpoints:
#ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(value = { IllegalArgumentException.class })
protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.CONFLICT, request);
}
}
There you have to define the status code to indicate user what kind of error was generated, 409 in order to indicate there was a conflict.
Also, there you can define a body including further information, either a string or a custom object containing an error message and description you offer to the client thru documentation.
You can use Zalando Problem, a library that implements application/problem+json.
https://github.com/zalando/problem
https://thecodingduck.blogspot.com/2023/01/best-practices-for-rest-api-design.html#standard_error

Spring MVC - REST Api, keep getting 400 Bad Request when trying to POST

i have a REST api service which should receive POST calls.
I'm using POSTMAN to test them, but i keep getting a 400 Bad Request Error, with no body, maybe i'm building bad my controller...
This is the controller
#PostMapping("/object/delete")
public ResponseEntity<?> deleteObject(#RequestBody long objectId) {
logger.debug("controller hit");
Object o = service.findByObjectId(objectId);
if(o!=null){
service.deleteObject(object);
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Using #RequestBody i should send the request in JSON, in this way:
{
"objectId":100
}
But i get a 400 error, and the strange think is that my logger logger.debug("controller hit"); it's not printed in logs...
Sending { "objectId":100 } would result in receiving an object X with an objectId attribute in your java method.
If you just need to send an id, you can use #PathVariable
#PostMapping("/object/{id}/delete")
public ResponseEntity<?> deleteObject(#PathVariable("id") long objectId) {
Also, consider using DeleteMapping instead of PostMapping to delete an object.

Resources