Laravel Input array of objects to api routes - arrays

I'm passing the following request to laravel api, but when I dump the input request, Laravel is returning an empty array.
{
"expense_type" : "payment",
"description" : "test",
"notes" : "My notes",
"expense_date": "2019-01-15",
"cost" : 100.50,
"group_id" : 1,
"shares" : [
{
"user_id" : 1,
"paid_share" : 100.50,
"owed_share" : 00.00
},
{
"user_id" : 2,
"paid_share" : 00.00,
"owed_share" : 50.25
},
{
"user_id" : 3,
"paid_share" : 00.00,
"owed_share" : 50.25
}
]
}
The output when dumping the input $request->all() is []
can some one help if there is something wrong in the request

When you send data in request as json data then $request->all() will always return empty. In order to access data in $request->all() variable you have to send form data not json data.
So, when json data is sent through api, you can access it as array in the controller like this:
$data = json_decode(file_get_contents("php://input"), true);
Now, you can access the values like $data['expense_type']
I hope you understand.

Related

Google Apps Script - Woocommerce Integration payload [duplicate]

running into problems between GAS and WC RESTv2, Im trying to create a simple product with custom attributes, while I am able to do so without any specific parameter the REST api return this error:
ERROR:
{"code":"rest_invalid_param","message":"Invalid parameter(s): attributes","data":{"status":400,"params":{"attributes":"attributes[0] is not of type object."},"details":{"attributes":{"code":"rest_invalid_type","message":"attributes[0] is not of type object.","data":{"param":"attributes[0]"}}}}}
// the product gets CREATED fine using this simple var data structure :
var data =
{
"name" : " TESTING HERE TOO",
//"sku" : "TESTINGINGING ",
"type" : "simple",
"regular_price" : "1.99",
"weight" : 10,
"manage_stock" : true,
"stock_quantity" : 10,
"description" : "testing \n" } ;
var surl = website + "/wp-json/wc/v2/products?consumer_key=" + keys + "&consumer_secret=" + scret;
var options =
{
"method": "POST",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
"payload": data
};
``` // -- the product DOES NOT get created using this :
var data =
{
"name" : " TESTING HERE TOO",
//"sku" : "TESTINGINGING ",
"type" : "simple",
"regular_price" : "1.99",
"weight" : 10,
"manage_stock" : true,
"stock_quantity" : 10,
"description" : "testing \n" } ;
"attributes" : [ { "variation" : "false", "options" : "[ANY]", "id" : 0.0, "name" : "Supplier", "position" : 0.0, "visible" :"false"} , { "variation" : "false", "options" : "[ANY]", "id" : 0.0, "name" : "Invoice", "position" :1.0, "visible" :"false"}]
Any body could shed some light where could be the issue?
In case anybody stumble here, here´s the solution:
if you´d like to know where´s the bug, here it is
var options =
{
"method": "POST",
//"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", -- it does NOT WORK like content type must be JSON
"contentType": "application/json",
"muteHttpExceptions": true,
"payload": JSON.stringify(data2) -- as long as JSON payload thus stringify accord.
//"payload": data2
};
when you have a JSON within an array in GAS, the only way REST api calls will understand is if you modify 2 things
"contentType": "application/json",
send the payload to rest api WC as json
"payload": JSON.stringify(data2)
trans for the javascript object into json so WC rest api can understand
done.

How to pass ArrayList as data to Postman

[ {"roleName" : "admin", "roleIds" : [1,2,3] },
{"roleName" : "editor", "roleIds" : [4,5,6] },
{"roleName" : "contributor", "roleIds" : [7,8,9]} ]
My code Looks like this and the error I am getting is, "Cannot generate variable name for non-typed Collection parameter type"

GrayLog not displaying messages that are Bulk inserted

I need to migrate millions of records from a SQL database to ES. Currently we insert records in ES via GELF HTTP, but only doing that one record at a time just isn't feasible.
I've been working on this a couple days and am new to both GrayLog and ElasticSearch. I'm trying to find a way to Bulk insert messages into ES and then have them display in GrayLog. I've been using Cerebro to monitor the indexes and the number of messages in each of them. When I do the Bulk insert, the message count does increase in the correct Index, however I can not see them in GrayLog.
Here is what I have:
var _elasticsearchContext = new ElasticsearchContext(ConnectionString, new ElasticsearchMappingResolver());
var connectionSettings = new ConnectionSettings(new Uri(ConnectionString))
.MapDefaultTypeIndices(m => m.Add(typeof(Auditing_Dev), "auditing-dev_0"));
var elasticClient = new ElasticClient(connectionSettings);
var items = new List<Auditing_Dev>();
//I loop through a DataReader creating new Auditing_Dev objects
//and add them to the items collection
var bulkResponse = elasticClient.Bulk(b => b.IndexMany(items, (d, doc) => d.Document(doc).Index("auditing-dev_0").Type("message")));
I get back a valid response and I see the document count increase in Cerebro in the auditing-dev_0 index. When I compare a message that I insert via Bulk to one that is inserted via HTTP request, the indexes and types are the same.
Message I insert:
{
"_index" : "auditing-dev_0",
"_type" : "message",
"_id" : "AVsWWn-jNp2NX1vOria1",
"_version" : 1,
"found" : true,
"_source" : {
"level" : 5,
"origin" : "10.80.3.2",
"success" : true,
"type" : "Company.Enterprise",
"user" : "stupid#dropdown.test",
"gl2_source_input" : "57193c1d0cf25a44afc31c15",
"gl2_source_node" : "5866cc80-382e-4287-ae5b-8a0a68a9a1f1",
"gl2_remote_ip" : "10.100.20.164",
"gl2_remote_port" : 52273,
"streams" : [ "578fbabe738a897c6d91336b" ]
}
}
Compared to one inserted via HTTP:
{
"_index" : "auditing-dev_0",
"_type" : "message",
"_id" : "e3d34d50-0a8a-11e7-84bb-00155d007a32",
"_version" : 1,
"found" : true,
"_source" : {
"level" : 5,
"gl2_remote_ip" : "192.168.211.114",
"origin" : "192.168.211.35",
"gl2_remote_port" : 2960,
"streams" : [ "578fbabe738a897c6d91336b" ],
"gl2_source_input" : "57193c1d0cf25a44afc31c15",
"success" : "True",
"gl2_source_node" : "5866cc80-382e-4287-ae5b-8a0a68a9a1f1",
"user" : "admin#purple-pink.test",
"timestamp" : "2017-03-16 22:43:44.000"
}
}
I see the _id is a different format, but does that matter?
In GrayLog there is only one Input and that is the one for GELF HTTP. Do I need to add a new Input?
Turned out to be the Timestamp field not being present. Who knew?

String from document meets value of array

I've got an array of Project ID's, for example:
[ 'ExneN3NdwmGPgRj5o', 'hXoRA7moQhqjwtaiY' ]
And in my Questions collection, I've got a field called 'project', which has a string of a project Id. For example:
{
"_id" : "XPRbFupkJPmrmvcin",
"question" : "Vraag 13",
"answer" : "photo",
"project" : "ExneN3NdwmGPgRj5o",
"datetime_from" : ISODate("2017-01-10T08:01:00Z"),
"datetime_till" : ISODate("2017-01-10T19:00:00Z"),
"createdAt" : ISODate("2017-01-10T08:41:39.950Z"),
"notificationSent" : true
}
{
"_id" : "EdFH6bo2xBPht5kYW",
"question" : "sdfadsfasdf",
"answer" : "text",
"project" : "hXoRA7moQhqjwtaiY",
"datetime_from" : ISODate("2017-01-11T11:00:00Z"),
"datetime_till" : ISODate("2017-01-11T17:00:00Z"),
"createdAt" : ISODate("2017-01-10T10:21:42.147Z"),
"notificationSent" : false
}
Now I want to return all documents of the Questions collection, where the Project (id) is one of the value's from the Array.
To test if it's working, I'm first trying to return one document.
Im console.logging like this:
Questions.findOne({project: { $eq: projectArray }})['_id'];
but have also tryed this:
Questions.findOne({project: { $in: [projectArray] }})['_id'];
But keep getting 'undefined'
Please try this.
Questions.find({project: { $in: projectArray }}) => for fetching all docs with those ids
Questions.findOne({project: { $in: projectArray }}) => if you want just one doc

Groovy & json: How to get the length of an array from json?

I am using curl to get some data, then parsing it with JsonSlurper.
The data structure is
"results" : [
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-30"
}
]
So if I'm not mistaken, the entire thing is considered an object. But there is an array in the object (results) which contains objects in that array.
I need to get the length of the results array. When I try to do json.result.length, I receive a null.
How can I get the length of the results array?
def list = ['curl', '-u', 'user:pass', "http://localhost:8081/..."].execute()
def json = new JsonSlurper().parseText(list.text)
println json.result.size()
What I see is, you are using incorrect property to get the size. Need to use results instead of result. Thats is the reason you are seeing that error as result is null(because there is no such property)
Here is working script and gets output as 3:
import net.sf.json.groovy.JsonSlurper
def jsonText='''{
"results" : [
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-30"
}
]
}'''
def json = new JsonSlurper().parseText(jsonText)
println json.results.size()
assert 3 == json.results.size(), "Array size is not matching"
It will be:
def response = ... // your response as text, stream..
def parsed = new JsonSluper().parse(response) // parseText if string
println parsed.results.size()
BTW: size() is for Collection, length for String, note method vs field. In groovy you can use size() for String as well.
{
"projects":
[
{
"platform": "java",
"name":"abc"
},
{
"platform": ".net",
"name":"abcd"
}]
}
for this json file list.json how to get json size or number of applications count.
below code worked for me in groovy as i was using in it my jenkinsfile.
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.io.FileType
def applicationCount()
{
jsonFile1 = 'list.json'
def json1 = readJSON file: jsonFile1
totalApplication = json1.projects.size()
println "count" + totalApplication
println "applicationname" + json1['projects'][0]['name']
}

Resources