cakephp crud plugin return validation errors - rest

When PATCHing to a record using the Crud plugin and Crud.Api listener, a successful PATCH returns a 200 OK with an empty data array in the response.
{
"success": true,
"data": []
}
When validation fails after a PATCH, a 422 Unprocessable Entity with the following response is returned:
{
"message": "A validation error occurred",
"url": "\/admin\/users\/edit\/4.json",
"code": 422,
"file": "\/app\/vendor\/friendsofcake\/crud\/src\/Listener\/ApiListener.php",
"line": 189
}
but I expected something like:
{
"success": false,
"data": [
"errors": [...]
]
}
https://crud.readthedocs.io/en/latest/listeners/api.html#http-put-edit
If success is false a HTTP response code of 422 will be returned,
along with a list of validation errors from the model in the data
property of the response body.
Does the plugin need to be configured to return the errors?

I'm not overly familiar with the Crud plugin, but that response looks like the default CakePHP exception renderer response, so I'd guess that you probably haven't configured your app to use the Crud exception renderer:
config/app.php
'Error' => [
'exceptionRenderer' => \Crud\Error\ExceptionRenderer::class,
// ...
],
Quote from the docs:
Note: However if you are using CakePHP 3.3+’s PSR7 middleware feature the exceptionRenderer config won’t be used and instead you will have to set the Error.exceptionRenderer config in config/app.php to 'Crud\Error\ExceptionRenderer' as following
See Crud Docs > Listeners > API > Exception handler

Related

Dialogflow - Firestore - Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500

I am trying for a fulfillment in Dialogflow using Firebase. There is data in Firestore and the intent is expected to retrieve the results based on the given parameter in the related intent. The intent is enables for webhook call. But the intent returns with one of the predefined responses.
I always get the error "message": "Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500."
Following is the Diagnostic Info from the test console
{
"responseId": "e27d24ba-cb14-4170-a7d8-a97314aee001-cad07fe1",
"queryResult": {
"queryText": "novaluron",
"parameters": {
"chemical": "novaluron"
},
"allRequiredParamsPresent": true,
"fulfillmentText": "This molecule is useful",
"fulfillmentMessages": [
{
"text": {
"text": [
"This molecule is useful"
]
}
}
],
"intent": {
"name": "projects/ppcagent-ahe9/agent/intents/6d9df198-9517-4d61-a480-87c158accdc5",
"displayName": "ChemicalDetails"
},
"intentDetectionConfidence": 0.3,
"diagnosticInfo": {
"webhook_latency_ms": 106
},
"languageCode": "en",
"sentimentAnalysisResult": {
"queryTextSentiment": {
"score": 0.3,
"magnitude": 0.3
}
}
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500."
}
}
Any help will be greatly appreciated.
This error could be due to different reasons, you can check these points:
Use of insecure connection.
You need to use HTTP requests. The service must use HTTPS and the URL must be publicly accessible in order for the fulfillment to function. DialogFlow does not support self-signed SSL certs. For information on SSL setup:
Permission errors.
Server files and folders need correct permissions and ownerships set in order to work properly. If Websites request files for which the server has no access then it will lead to an error.You can see more documentation about permission.
Bad scripting.
You need to check the code and check if there are any errors and modify them.

Validation Error (Error Code 422) while trying to POST Hyperledger Transaction on REST API using POSTMAN

I was trying to test Transactions via Playground, Composer-Rest-server and Finally POSTMAN.
The Transactions worked perfectly on Playground (Figure 1 and 2) and also on the Composer-Rest-Server (Figure 3 and 4). But then I tried the same using POSTMAN, for which I am getting an Error ( Status Code 422 )(Figure 5).
I'm using the basic-sample-network. And the Transaction just updates the value of the asset.
Figure 1 - Executing Sample Transaction On Playground
Figure 2 - Updated Value of Asset #3952
Figure 3 - Executing the Transaction on the composer Rest Server
Figure 4 - Updated Value of Asset #3952 after the Rest Server Transaction
Figure 5 - Error While Using POSTMAN
The Error
"error": {
"statusCode": 422,
"name": "ValidationError",
"message": "The `org_example_basic_SampleTransaction` instance is not valid. Details: `asset` can't be blank (value: undefined); `newValue` can't be blank (value: undefined).",
"details": {
"context": "org_example_basic_SampleTransaction",
"codes": {
"asset": [
"presence"
],
"newValue": [
"presence"
]
},
"messages": {
"asset": [
"can't be blank"
],
"newValue": [
"can't be blank"
]
}
},
"stack": "ValidationError: The `org_example_basic_SampleTransaction` instance is not valid. Details: `asset` can't be blank (value: undefined); `newValue` can't be blank (value: undefined).\n at ...
What is the reason for this Error and How can I solve it?
You have to post data in JSON format.

Creating Issue using GitHub API

I am trying to create an Issue in my own repo using Github API, but for some reason it keeps throwing me an error
Route::post('/issue/create/{repo}',function ($_repo){
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://api.github.com',
// You can set any number of default request options.
// 'timeout' => 2.0,
]);
$url = '/repos/rehan-dckap/'.$_repo.'/issues';
// Set various headers on a request
$response = $client->request('POST', $url, [
'query' => [
'title' => 'IssueCreation',
'body' => 'ThPI',
'assignee' => '',
'milestone' => 1,
'labels' => [],
'assignees' => []
],
'headers' => [
'Authorization' => 'Bearer TOKENTOKENTOKENTOKEN'
]
]);
return response($response->getBody());
});
ERROR
Client error: POST https://api.github.com/repos/rehan-dckap/qatouch-api-docs/issues?title=IssueCreation&body=ThPI&assignee=&milestone=1 resulted in a 422 Unprocessable Entity response: { "message": "Invalid request.\n\nFor 'links/0/schema', nil is not an object.", "documentation_url": "https://develo (truncated...)
Can someone guide me?
I've taken quite a bit of time to try and understand what the problem is here, but without running the code itself it will be a bit tricky. Can you provide an online sandbox with that code so I can play with it? I'm happy to provide the token myself. There's two main things here.
First the 422 generally means that there was an error parsing the payload. Looking at your payload, and the error message I would try to start by removing all non-mandatory fields starting by the arrays. If we look at the error message it's saying Nil is a not an object. My best guesses would be problems with the arrays or the assignee string.
Overall my tip in these cases is to reduce the API call to the bare functional. minimum and try to isolate the problem. I would go as far as using the GitHub Example they've posted on the API page and even remove the assignee since it's been deprecated:
{
"title": "Found a bug",
"body": "I'm having a problem with this.",
"milestone": 1,
"labels": [
"bug"
]
}
Hope this helps.
here you can check the error code: https://developer.github.com/v3/
Sending invalid fields will result in a 422 Unprocessable Entity response.
HTTP/1.1 422 Unprocessable Entity
Content-Length: 149
{
"message": "Validation Failed",
"errors": [
{
"resource": "Issue",
"field": "title",
"code": "missing_field"
}
]
}

Wiremock bodyFileName templating

I'm using Wiremock to stub out some API calls made by mobile clients.
Struggling to get templated filename from request.
Can anyone confirm if this should even work with Wiremock standalone pls?
"response": { "status": 200, "bodyFileName": "Account-{{jsonPath request.body '$.user.identity'}}.json”}
I've got static files to be returned fine, just seems like bodyFileName doesn't like templating.
Example:
I configure wm with following Json:
{
"request": {
"method" : "GET",
"url": "/users/D8428899330"
},
"response": {
"status": 200,
"bodyFileName": "user-{{request.path.[1]}}.json"
}
}
Then when I attempt the url, http://localhost:9696/users/D8428899330 I get the following error,
HTTP ERROR: 500 Problem accessing /users/D8428899330. Reason:
java.lang.RuntimeException: java.io.FileNotFoundException:
/Users/iainframe/Documents/__files/user-{{request.path.[1]}}.json (No
such file or directory)
Should indicate that the file user-D8428899330.json resides in the correct location as I've hard coded it and it returns it ok. The command to start WireMock is:
java -jar ~/Documents/wm.jar --port 9696 --global-response-templating --verbose --root-dir /Users/iainframe/Documents/
The following response definition works fine for me with Wiremock 2.25.1 using the response template transformer.
"response": {
"transformers": ["response-template"],
"status": 200,
"bodyFileName": "user-{{jsonPath request.body '$.userid'}}.json" }
and this also works fine:
"response": {
"transformers": ["response-template"],
"status": 200,
"bodyFileName": "user-{{request.path.[3]}}.json" }
Interesting, I was running into the same problem and was able to solve it by starting WireMock with --global-response-templating. But you are using that parameter too... If it matters, I'm using WireMock 2.33.2.

"Resource Not Found" message received when sending a query to Keen IO API

I am using Advanced REST Client tool to test a data pull from the Keen IO API, and think getting the request right, but not getting the data. Getting "resource not found" error. This can also be done via CURL.
Headers: Authorization:
Content-Type: application/json
actual request: GET /3.0/projects//queries/saved/Sponsorships/result HTTP/1.1
HOST: api.keen.io
authorization:
content-type: application/json
Base URL used: https://api.keen.io
Any ideas as to what may be doing wrong?
The saved query name is capitalized "Sponsorships". Make sure your saved query name is lower-cased, not camel or title-cased. To be sure that you are getting the correct saved query name.
Also, you may want to first obtain a list of all saved queries as a reference:
GET /3.0/projects/<project_name>/queries/saved HTTP/1.1
HOST: api.keen.io
authorization: <your_key>
content-type: application/json
You will get something like this:
[
{
"refresh_rate": 0,
"last_modified_date": "2016-12-20T01:09:54.355000+00:00",
"query_name": "",
"created_date": "2016-12-20T01:09:54.355000+00:00",
"query": {
"filters": [],
"latest": 100,
"analysis_type": "extraction",
"timezone": "UTC",
"timeframe": "this_30_days",
"event_collection": ""
},
"metadata": {
"visualization": {
"chart_type": "table"
},
"display_name": ""
},
"run_information": null
}
]
FWIW, I also have seen the "Resource not found" error when writing data to an event if the project is not correctly set up. For example, passing in the wrong project_id or write_key or if the project was deleted from your Keen.io account.