Using postman raw testing spring-boot controller failed - spring-boot

Here is the controller:
Here is the postman:
Via form-data, I can get caseId in my controller.
But raw with header, I can't.
I don't know why... Is there anything wrong with my controller ?
Please help, thanks.
edit 1:
Yeah. Add something more
We know, springMVC will bind data for us, but when we use POST request and put data in body via raw and Content-Type:application/json, spring will still bind data? request.getInputStream() will only call once.
edit 2:
I found a way to get the raw.
get the json string.
edit in 11/29/2017
I found that:
Post with raw, I need to use #RequestBody to recive the value.

Here are the example of how to retrieve data using POSTMAN and bind with SpringMVC
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if (users.isEmpty()) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
You may refer to this article : Spring Boot Rest API Example

Can u bind request param as below and check :
public Object getTcaseByCaseId(#RequestParam("caseId") String caseId) {

Related

How to just get the data using CRUD POST method?

I have developed Small Spring boot Rest api app. I can able to get the data or create new record and search with paging and sorting.
Now i'm looking for provide input data in body to get the data instead of providing in URL with GET method. Is this method also default function ? Please advise.
public interface CodeTextRepository extends PagingAndSortingRepository<CodeText, Long> {
}
How to write POST method to just get the data ?
http://localhost:8080/api/code
method : POST
{
"code":1
}
If I understand you correctly, you want to create a controller that will get the a model as body parameter ({ "code": 1 }) in a POST method and then do something with it.
To do that, you can create a controller that looks like the following (I inserted pseudo-code as an example):
#RestController
#RequestMapping(value = "/api/code")
public class CodeTextController {
private CodeTextRepository codeTextRepository;
// constructor injection
public CodeTextController(CodeTextRepository codeTextRepository) {
this.codeTextRepository = codeTextRepository;
}
#PostMapping
public CodeText postCodeText(#RequestBody CodeTextRequest codeTextRequest) {
// some code to get from the DB
return codeText;
}
}
public class CodeTextRequest {
private int code;
// getters and setters
}
Simply add Accept header to the request, like
accept: application/json
Spring Data-Rest will return the body after a POST request if either the returnBodyOnCreate flag was explicitly set to true in the RepositoryRestConfiguration OR if the flag was NOT set AND the request has an Accept header.
You can set the flag directly during configuration, or you can set it via the application.properties:
spring.data.rest.returnBodyOnCreate = true
you can also set it separately for update:
spring.data.rest.returnBodyOnUpdate = true
---- edit
Maybe I misunderstood your question. If you simply want to GET an existing data using POST method, then DO NOT DO IT AT ALL! That's not a REST API any more. There must be some reason you want to do it, but you should try do resolve that original problem instead in another way!

Returning JSON response from spring controller goes as html instead of JSON in javascript

I have one spring controller which is sending JSON response to the ajax call present in my script. I have used #ResponseBody in the controller method which directly sends JSON as response when it is invoked via ajax call.
After when I added the JsonSanitizer.sanitize(myJsonString), it is returning as html in the ajax response instead of JSON. Because of that, I am unable to parse the json object now.
Example Code:
#ResponseBody
#RequestMapping(value="/getJson" method="GET")
public String fetchJsonDetails(MyObj obj) {
//DB call based on my object..
//Previously added
//return new Gson().toJson(obj);
//New line added now
return JsonSanitizer.sanitize(new Gson().toJson(obj));
}
After the above added new line, response is coming as html instead of JSON.
Please suggest me to achieve this and let me know if anything required further.
Thanks in advance.
You may specify the kind of return you do:
#ResponseBody
#GetMapping(value="/getJson", produces="application/json")
public String fetchJsonDetails(MyObj obj) {
// DB Call
return JsonSanitizer.sanitize(new Gson().toJson(obj));
}
You can also use
import org.springframework.http.MediaType;
...
#GetMapping(value="/getJson", produces=MediaType.APPLICATION_JSON_VALUE)

Validate empty request

I am developing a SpringBoot Application. For a POST end-point, there is NO request body to be passed. My service is working fine. But its also working when I pass some values in the body of the request. How can I validate and return a BAD REQUEST if something is passed in the body of request which should ideally remain empty for this request?
*#RequestMapping(value = "/sample/customers", method = POST)
public Customer session() {
return customerService.getCustomer();
}*
You should not use POST for data retrieval.
You'll need 2 methods. Here is an example code for the save:
#ResponseStatus(value = HttpStatus.CREATED)
#RequestMapping(value = "/sample/customers", method = POST)
public Customer save(#RequestBody CustomerRequestDto customerRequestDto) {
return customerService.save(customerRequestDto);
}

Post data in asp.net web API with header

Hi every one I am new to Asp.net Web API and I had my question post data using asp.net Web API and got my answer accepted.
This is an extension to the same question I want to post data with some header value in the Postman and my code is as follows
public HttpResponseMessage PostCustomer([FromBody] NewUser userData, string devideId)
{
//My code
return response;
}
When I hit this in Postman passing values in JSON format in BODY - raw I got message as follows
No HTTP resource was found that matches the request URI
No action was found on the controller that matches the request.
Please help me.
It looks like you have added some additional devideId string parameter to your action. Make sure that you are supplying a value to it as a query string when making the request:
POST http://localhost:58626/api/customers?devideId=foo_bar
If you don't want to make this parameter required then you should make it optional (in terms of optional method parameter in .NET):
public HttpResponseMessage PostCustomer([FromBody] NewUser userData, string devideId = null)
{
...
}
Now you can POST to http://localhost:58626/api/customers without providing a value for this parameter.
Remark: You don't need to decorate a complex object type (such as NewUser) with the [FromBody] attribute. That's the default behavior in Web API.
UPDATE: Here's how you could read a custom header:
public HttpResponseMessage PostCustomer(NewUser userData)
{
IEnumerable<string> values;
if (this.Request.Headers.TryGetValues("X-MyHeader", out values))
{
string headerValue = values.FirstOrDefault();
}
...
return response;
}

Web API 2 attribute routing returning 404

I'm having trouble getting the Web API 2 attribute routing to work.
I've been trying everything I could find this whole evening but I can't find the problem.
What I want to achieve is the following:
Make a POST request to http://localhost:xxxx/api/chat/joingroup/1234 to get to the following API call:
[Route("joingroup/{id}")]
[HttpPost]
public async Task<IHttpActionResult> JoinGroup(string id, string connectionID)
{
await hubContext.Groups.Add(connectionID, id);
return Ok(hubContext.Groups.ToString());
}
This keeps getting me a http 400 message.
{"message":"No HTTP resource was found that matches the request URI 'http://localhost:41021/api/chat/joingroup/123'.",
"messageDetail":"No action was found on the controller 'Chat' that matches the request."}
But sending a post to: http://localhost:41021/api/chat/sendmessage/pm/123123 and also to http://localhost:41021/api/chat/joingroup gives me a 200
The chatcontroller:
[RoutePrefix("api/chat")]
public class ChatController : ApiController
{
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
[...]
[Route("joingroup/{id}")]
[HttpPost]
public async Task<IHttpActionResult> JoinGroup(string id, string connectionID)
{
await hubContext.Groups.Add(connectionID, id);
return Ok(hubContext.Groups.ToString());
}
HTTP POSTS to http://localhost:xxxx/api/chat/sendmessage are working fine.
I cannot figure out why it isn't going to the correct method when I'm calling a POST on http://localhost:xxxx/api/chat/joingroup/1234.
SOLUTION:
The solution was to reference both values that are needed in the JoinGroup method, id and connectionID. Now the request will hit this method.
Using:
http://localhost:xxxx/api/chat/joingroup/john?connectionid=123 will work.
I noticed two things on the code you sent through:
the path you POST to is: localhost:xxxx/joingroup/1234 , this
should be localhost:xxxx/api/chat/joingroup/1234
because you have 2 parameters for the joingroup, you will need to pass both of them through, may be like this localhost:xxxx/api/chat/joingroup/1234?connectionID=value or you can pass it on the request body
if the connectionID is optional you can modify the method to use option al parameters like this
public string JoinGroup(string id, string connectionID = "")
please let me know if this helps.
Thanks
Ashraf
I assume the connectionID parameter references the POSTed data. The easiest thing to make it work is to decorate it with the [FromBody] attribute and put an = in front of the value being sent like this: =MyConnection1.
Web API expects an object with properties or an array otherwise. Alternatively, you can wrap the connection ID with a custom class and pass it serialized as JSON/XML.

Resources