Custom Guzzle serialization - php

I would like to have a custom serialization in Guzzle.
I'm setting a POST application/json request, but my object is serialized with its name (professionalSession) at the beginning, i.e.:
{
professionalSession :
{
param1 : "asdf",
param2 : "jkl;",
...
}
}
That is inconsistent with the REST API I'm trying to call. (className is hidden as one of the parameters).
This is my definition in serviceDescription.json:
"PostAuthentication": {
"httpMethod": "POST",
"uri": "/xxx-person-service/session",
"summary": "Posts the session object",
"type": "json",
"responseClass": "XXX\\WebServicesClientBundle\\Entity\\ProfessionalSession",
"parameters":{
"session": {
"location": "json",
"required": true
},
"session-identifier": {
"location": "header",
"required": true,
"sentAs": "HTTP_X_SESSION_KEY"
}
}
}
I would like to use serviceDescription.json and only override its 1 parameter (by produce json myself).
I tried changing the location of param to body (as it was said in SO somewhere), but Content-Type is not being properly set to application/json.
How can I do it? Thanks!

I will reply as there are no responses yet and I've overcame this problem.
Changing the location of param to body was good approach as it removes that top level JSON element. (This was signaled as a problem, but still - this is how Guzzle behaves.)
To change request to application/json you can use following description in serviceDescription.json:
"PostAuthentication": {
"httpMethod": "POST",
"uri": "/xxx-person-service/session",
"summary": "Posts the session object",
"responseClass": "XXX\\WebServicesClientBundle\\Entity\\ProfessionalSession",
"parameters":{
"session": {
"location": "body",
"required": true
},
"session-identifier": {
"location": "header",
"required": true,
"sentAs": "HTTP_X_SESSION_KEY"
},
//THIS is what you need:
"content-type": {
"location": "header",
"static": true,
"required" : true,
"default" : "application/json",
"sentAs" : "Content-Type"
}
}
},

Related

How to fix error 422 on axios post request?

I am trying to populate a already built php database using axios requests, however i keep receiving 422 error and I don't understand what I am missing. Could you please help me :)
This is the error that i get:
xhr.js:177 POST URL/data 422 (Unprocessable Entity)
This is the Post request schema of the DB:
"post": {
"summary": "Post new data row",
"description": "Post new data row",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "string",
"example": "{\"test\":1}"
},
"type": {
"type": "string",
"example": "1"
},
"status": {
"type": "integer",
"example": 1
}
},
"required": [
"data",
"type"
]
}
}
}
},
"responses" :{
"422": {
"description": "Error",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "Invalid input"
}
This is my code,
I have several switch cases and they should all work in the same manner:
case "rezervariContact" : {
const {type, titlu, description, phone, email} = this.state;
const contactData = {
type: this.state.type,
data:{
type,
data :{
titlu, description, phone, email
}
},
status:true
}
data = {...contactData};
}
}
await axios({
method: "post",
headers: { "Content-Type": "application/json",
'Accept': '*/*' },
body:data,
url : 'http://xxxxxxxxx.ro/data'
})
.then(function (response) {
console.log("RespResolved::",response.config.params);
})
.catch(function (response) {
console.log("catchErrResp::",response);
});
}
Please if you can spot something let me know.
422 probably means your inputted data is invalid.
The reason for this depends on the server. You could try referring to any documentation for the API/server you are trying to reach.
Check document on http://xxxxxxxxxx.ro/data! It means your post data is valid but server can not hand it correctly!

Google Fit API Cannot add most of the scopes

I am using the Google Fit REST API for our current project. We can add some of the data sources but there are some we cannot add. We already followed the documentations. Some of the request are returning this kind of error message (we even tried in their OAuth playground)
"error": {
"status": "INVALID_ARGUMENT",
"message": "Data type does not match well-known data type with the same name",
"code": 400,
"errors": [
{
"reason": "invalidArgument",
"message": "Data type does not match well-known data type with the same name",
"domain": "global"
}
]
}
What we are trying to add is this data source which we already allow the permission scopes of
https://www.googleapis.com/auth/fitness.activity.read
https://www.googleapis.com/auth/fitness.activity.write
{
"application": {
"name": "PersonalPulse",
"version": "1.0.0"
},
"dataType": {
"name": "com.google.activity.exercise",
"field": [
{
"name": "exercise",
"format": "integer"
},
{
"name": "repetitions",
"format": "integer"
},
{
"name": "resistance type",
"format": "integer"
},
{
"name": "resistance",
"format": "floatPoint"
},
{
"name": "duration",
"format": "integer"
}
]
},
"device": {
"manufacturer": "browser",
"model": "browser",
"type": "unknown",
"uid": "2",
"version": "10"
},
"type": "derived"
}
We followed the instructions based on the documentations here
https://developers.google.com/fit/datatypes/activity#workout
We are using PHP/Laravel framework for the fitness api and cURL for the http requests. If someone got an idea why we got the error please help. Thanks.
You can also try in the google playground here and paste the scopes https://developers.google.com/oauthplayground/
The first problem with your request is that you're passing in the exercise is an integer field, but the documentation says that you need to pass in one of an enumerated set of strings (I don't know why it says int there, but if you click the "Accepted values", you can see those definitely aren't integers...).
However, it would be easier if you didn't specify the fields at all. Simply specify the data type name:
// ...
"dataType": {
"name": "com.google.activity.exercise",
}
// ...
and the correct fields will be filled in on the backend and returned to you.

POST Nested Json to API With Jquery Ajax & Get Response With PHP

I want to Post a Json string or PHP array to a Restful API and get the response without reloading the page. So, I want to use Ajax and/or jquery. So far, I'm failing miserably. my code is below.
I've tried several jquery methods - some using stringify and others just sending raw json. I'm not getting enough response or error of any kind to know where I need to look to solve the problem.
$(".avm_zip").on("click", function() {
$.ajax({
url: "REMOVED",
type: "POST",
data: {
"Header": {
"UserId": "REMOVED",
"Password": "REMOVED",
"SourceApplication": "Dev Service Tester"
},
"Property": {
"StreetAddress": "10345 W Briar Oaks Dr # E",
"City": "Stanton",
"State": "CA",
"Zip": "90680",
"APN": null,
"PropertyType": null
},
"Order": {
"CustomerOrderReference": "Test LITE",
"PreferenceTableName": "VeroLITE TEST",
"Price": null,
"Credit": null,
"AdditionalFields": null
}
},
dataType:'json',
success: function (response) {
alert("Success");
},
error: function(error){
alert("Something went wrong");
},
});
The API is more robust and centered on XML. Getting the basic call & retrieval set up using Json had challenges because of this. So, it is possible that is bleeding over into this effort.

ROWS not returning in Youtube Analytics API?

I have made a request to this url: https://www.googleapis.com/youtube/analytics/v1/reports with the metrics: likes and dislikes.
The echoed response:
{
"kind": "youtubeAnalytics#resultTable",
"columnHeaders": [
{
"name": "likes",
"columnType": "METRIC",
"dataType": "INTEGER"
},
{
"name": "dislikes",
"columnType": "METRIC",
"dataType": "INTEGER"
}
]
}
Where are the rows and the actual data that i requested? In the documentation this is what is supposed to return when i request data from youtube:
{
"kind": "youtubeAnalytics#resultTable",
"columnHeaders": [
{
"name": string,
"dataType": string,
"columnType": string
},
... more headers ...
],
"rows": [
[
{value}, {value}, ...
]
]
}
But i get no "rows": [] data. Does my account just not have any analytics or did i do something wrong?
If i cange the alt=json to alt=csv i get null returned.
From the docs: 'If no data is available for the given query, the rows element will be omitted from the response.'

Google Drive SDK: Inserting a file results in Untitled in PHP

I do know about the two previous posts:
PHP Google Drive API - File Upload Only As "Untitled"-File Or Just Without Content
Google Drive PHP SDK saves an Untitled file
But apart from the answer 'are you sure you're using the latest release', none of the askers have come back to say if yes or no or if they've managed to find an answer.
Because I'm doing the same thing as them, I'm using the latest apiDriveService.php with the last revision dated from June 2012.
The data is correctly found but when you arrive at the insert line, clearly, something wrong happens.
And I don't understand why for the SDK php example, it seems to go correctly.
Is this a problem in the Google Api Console? Or do I need to encode the data in something special?
EDIT: in the apiDriveService file, I can see this line:
$this->files = new FilesServiceResource($this, $this->serviceName, 'files', json_decode('{"methods": {
"insert": {"scopes": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file"],
"parameters": {"convert": {"default": "false", "type": "boolean", "location": "query"}, "targetLanguage": {"type": "string", "location": "query"}, "sourceLanguage": {"type": "string", "location": "query"}, "ocrLanguage": {"type": "string", "location": "query"}, "pinned": {"default": "false", "type": "boolean", "location": "query"}, "ocr": {"default": "false", "type": "boolean", "location": "query"}, "timedTextTrackName": {"type": "string", "location": "query"}, "timedTextLanguage": {"type": "string", "location": "query"}}, "supportsMediaUpload": true, "request": {"$ref": "File"}, "mediaUpload": {"maxSize": "10GB", "accept": ["*/*"], "protocols": {"simple": {"path": "/upload/drive/v2/files", "multipart": true}, "resumable": {"path": "/resumable/upload/drive/v2/files", "multipart": true}}}, "id": "drive.files.insert", "httpMethod": "POST", "path": "files", "response": {"$ref": "File"}}, ...);
In the parameters I'm sending, there is data and mimetype:
$created = $apiService->files->insert($driveFile, array('data' => $data,'mimeType' => $mimeType));
And in the insert function, there is an array_merge with data and mimetype:
public function insert(DriveFile $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new DriveFile($data);
} else {
return $data;
}
}
I don't find them in the insert part of the line I've mentionned above. Is it tied to that?
Just check out the current API Client from Google SVN.
http://code.google.com/p/google-api-php-client/source/checkout
We had the same problem but after doing an svn checkout, it magically worked and thanks to Alain and Claudio for their swift response on this.

Categories