Accessing JPA Data with REST fails No suitable HttpMessageConverter found - java

I have been battling with this for a while and cant find a solution. I am running the SpringBoot guides and the Accessing JPA Data (http://spring.io/guides/gs/accessing-data-rest/) with REST is not working.
Just downloading it and running it runs fine allowing a GET call to
http://localhost:8080/people
using POSTMAN. However whenever I try a PUT or POST I get the following error
{
"cause": null,
"message": "No suitable HttpMessageConverter found to read request body into object of type class hello.Person from request with content type of text/plain;charset=UTF-8!"
}
The json I am passing with the PUT is
{
"firstName": "Dave",
"lastName": "Something"
}
This is just running the vanilla project with no changes. Lots of the other guide projects work fine so I know MVN, Spring boot etc are working ok.
Have tried a lot of forums but nothing suggested works.
Any help would be greatly appreciated.
Thanks
Dave

Your POST request has a content type of text/plain and the server doesn't know how to convert plain text into a hello.Person instance.
You need to tell the server that you're sending JSON by setting the Content-Type header of the request to application/json

I used Google Chrome's Postman extension and sent raw JSON { "firstName": "Frodo", "lastName": "Baggins" }. That worked.
Keep in mind to specify the HTTP header Content-Type: application/json.

Content-Type:application/json try to remove the space between content-type:* and application in the header .

Make sure you have selected the
Body->RAW->Json in the Api Client and try it worked for me.

Related

PayPal Order PATCH call throws bad request

I'm working on a PayPal payment integration using a Java Springboot microservice where in an order is created on PayPal, i'm retrieving the order details from the paypal successfully. Now I want to update the order in the PayPal by adding an attribute invoice_id. But, when the Update Order(PATCH) is being called, Paypal throws a bad Request.
Doc link : https://developer.paypal.com/docs/api/orders/v2/#definition-order_capture_request.customized_x_unsupported_3218_order_application_context
PATCH https://api-m.sandbox.paypal.com/v2/checkout/orders/{{order_Id}}
Request :
{
"op": "add",
"path": "/purchase_units/#reference_id=='default'/invoice_id",
"value": "123456"
}
Error Response: [{"name":"INVALID_REQUEST","message":"Request is not well-formed, syntactically incorrect, or violates schema.","debug_id":"1ef2afd17aa1p", "details":[{"field":"/","location":"body","issue":"MALFORMED_R... (421 bytes)]
Can someone help me on this please.
I tried out multiple things like changing the request body. But, it doesn't seem to be working.

Resource contains external reference to URL xxx but this server is not configured to allow external references

Seeing such message in the logs:
11 Apr 2022 12:40:25 -- ERROR -- Class: jdk.internal.reflect.GeneratedConstructorAccessor245, Method: newInstance, Error: HTTP 400 : HAPI-0507: Resource contains external reference to URL "http://web-fhir/fhir/Task/9589a07d-6022-4b57-afeb-c9149679eedc" but this server is not configured to allow external references
As I understand it comes from line
MethodOutcome outcome = fhirUtil.getFhirClient(localFhirStorePath).update().resource(taskBasedOnRemoteTask)
.execute();
I saw in the logs the PUT request is being made to http://fhir.openelis.org:8080/fhir/Task/001a3df6-98c6-4c41-9ead-1387f55e4ecb
but when I make this put request in postman, I get
{
"resourceType": "OperationOutcome",
"text": {
"status": "generated",
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\"><h1>Operation Outcome</h1><table border=\"0\"><tr><td style=\"font-weight: bold;\">ERROR</td><td>[]</td><td><pre>HAPI-0449: Incorrect Content-Type header value of "FHIR" was provided in the request. A FHIR Content-Type is required for "UPDATE" operation</pre></td>\n\t\t\t</tr>\n\t\t</table>\n\t</div>"
},
"issue": [
{
"severity": "error",
"code": "processing",
"diagnostics": "HAPI-0449: Incorrect Content-Type header value of \"FHIR\" was provided in the request. A FHIR Content-Type is required for \"UPDATE\" operation"
}
]
}
I see those logs have prefix HAPI and number. Where can I find the information about those errors meanings and how to solve them?
How to understand
"A FHIR Content-Type is required for "UPDATE" operation" ?
I have addded FHIR content type, why it still complains?
How to configure server to allow external references?
"FHIR" isn't a valid Content-Type. The allowed content types are here: http://build.fhir.org/http.html#mime-type
For you, you'd need to use application/fhir+json
Assuming you are using the hapi jpastarter project. To allow external resources you have to change this line
How my lead solved this: there is a service in docker-compose.yml fhir.someservice.org
fhir.someservice.org:
image: "hapiproject/hapi:v5.6.0"
environment:
hapi.fhir.allow_external_references: "true"
I removed other code from the service code but just left what he changed - changed image and added environment variable with this config. I do not know why this works but it works, maybe will be useful for someone.
Also removed
restart: always
and volumes: and secrets:
but those maybe are just a clean up and irrelevant.

HttpClientErrorException 406 null is thrown in rest template spring mvc [duplicate]

In my Ruby on Rails application I tried to upload an image through the POSTMAN REST client in Base64 format. When I POST the image I am getting a 406 Not Acceptable Response. When I checked my database, the image was there and was successfully saved.
What is the reason for this error, is there anything I need to specify in my header?
My request:
URL --- http://localhost:3000/exercises.json
Header:
Content-Type - application/json
Raw data:
{
"exercise": {
"subbodypart_ids": [
"1",
"2"
],
"name": "Exercise14"
},
"image_file_name": "Pressurebar Above.jpg",
"image":"******base64 Format*******"
}
Your operation did not fail.
Your backend service is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.
Ref: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Find out the response (content type) returned by Service.
Provide this (content type) in your request Accept header.
http://en.wikipedia.org/wiki/HTTP_status_code -> 406
406 Not Acceptable
The resource identified by the request is only capable of generating response entities which have content characteristics not
acceptable according to the accept headers sent in the request.
406 happens when the server cannot respond with the accept-header specified in the request.
In your case it seems application/json for the response may not be acceptable to the server.
You mentioned you're using Ruby on Rails as a backend. You didn't post the code for the relevant method, but my guess is that it looks something like this:
def create
post = Post.create params[:post]
respond_to do |format|
format.json { render :json => post }
end
end
Change it to:
def create
post = Post.create params[:post])
render :json => post
end
And it will solve your problem. It worked for me :)
"Sometimes" this can mean that the server had an internal error, and wanted to respond with an error message (ex: 500 with JSON payload) but since the request headers didn't say it accepted JSON, it returns a 406 instead. Go figure. (in this case: spring boot webapp).
In which case, your operation did fail. But the failure message was obscured by another.
You can also receive a 406 response when invalid cookies are stored or referenced in the browser - for example, when running a Rails server in Dev mode locally.
If you happened to run two different projects on the same port, the browser might reference a cookie from a different localhost session.
This has happened to me...tripped me up for a minute. Looking in browser > Developer Mode > Network showed it.
const request = require('request');
const headers = {
'Accept': '*/*',
'User-Agent': 'request',
};
const options = {
url: "https://example.com/users/6",
headers: headers
};
request.get(options, (error, response, body) => {
console.log(response.body);
});
Changing header to Accept: */* resolved my issue and make sure you don't have any other Accept Header
In my case, I added:
Content-Type: application/x-www-form-urlencoded
solved my problem completely.
If you are using 'request.js' you might use the following:
var options = {
url: 'localhost',
method: 'GET',
headers:{
Accept: '*/*'
}
}
request(options, function (error, response, body) {
...
})
In my case for a API in .NET-Core, the api is set to work with XML (by default is set to response with JSON), so I add this annotation in my Controller :
[Produces("application/xml")]
public class MyController : ControllerBase {...}
Thank you for putting me on the path !
It could also be due to a firewall blocking the request. In my case the request payload contained string properties - "like %abc%" and ampersand symbol "&" - which caused the firewall to think it is a security risk (eg. a sql injection attack) and it blocked the request. Note here the request does not actually go to the server but is returned at the firewall level itself.
In my case, there were no application server logs generated so I knew that the request did not actually reach the server and was blocked before that. The logs that helped me were Web application firewall (WAF) logs.

How to post "application/octet-stream" content type to RestAPI using RestAssured

I'm trying to post "application/octet-stream" content type to RestAPI using RestAssured. But it's getting failed and throwing error like:
Don't know how to encode the ××××× as a byte stream. I have tried to use encoderConfig().encodeContentTypeAs() method but this meyhod is not available for RestAssured. Please suggest if there is any other way around to resolve this.
I was facing the same issue and it turned out to be not a multipart upload but through the body.
Please do not mention the header explicitly as application/octet-stream.
I was able to solve it and got it working successfully with simple code ,
given(). header("Content-Type","text/csv"). headers("Authorization","bla-
blah","Header 2","blahblah").
body(new File("your-file-[ath")). when(). post("/post-url");

REST API Design sending JSON data and a file to the api in same request

I am creating a REST API on top of an existing application. One of the features takes in a json data along with a file uploaded by the user.
I am unsure how to send a file AND json data in the same request to the REST API?
I have the json part working and I test that using curl:
curl -XPOST http://localhost:8080/myapp/foo -d '{"mydata": {
"name": "somename",
"gender": "male"
}}'
//I would like to send an image (say, profile image) with the above request as well.
I'm using a grails application so I get this data in my controller like so: new Foo(params.mydata).
Question
Is it possible to send JSON data and a file in the same request to the API? If so, how can I do it using curl or REST Console (chrome extension)
What would be the contentType of this request?
I'm open to sending data in another format if it means that I can send file and other data (strings) within the same request. I'm not tied on JSON
Update
I found another SO question which is asking the same thing. From the answer to that question it seems there are only three choices and none of which say that its possible to send both, json data and file, within the same request. Which is very discouraging...I will keep this question open to see if anyone has other ideas.
I think the "right" way to do this is with a multipart message. That way, you can post up both the JSON and the Image with their corresponding correct MIME type. The wikipedia article on multipart mime types has an example of what this would look like. It looks like both Apache httpcommons and Jersey support this sort of thing, and apparently curl does too!

Categories

Resources