I am trying to build a multidimensional array to a query string for an API request.
$key = env('GRAPHHOPPER_API_KEY', null);
$baseUrl = "https://graphhopper.com/api/1/route";
$formData = [
'point' => [request()->input('point1'), request()->input('point2')],
'key' => $key,
];
$queryStr = http_build_query($formData);
$url = $baseUrl.'?'.$queryStr;
try {
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', $url, [
\GuzzleHttp\RequestOptions::JSON => $formData
]);
$result = json_decode($response->getBody(), true);
dd('result', $result);
}
catch (\Exception $e)
{
return response()->json([
'status' => 0,
'message' => $e->getMessage(),
'trace' => $e->getTrace()
]);
}
This is what it looks like when I DD out:
The error from API tells me it's expecting two points so I guess I am not building the query string collecting
Docs: https://docs.graphhopper.com/#tag/Routing-API
Error:
resulted in a 400 Bad Request response:\n{\"message\":\"Specify at
least 2 points\"}
The docs page you linked to shows you how to structure the querystring data (see the testbed on the right hand side)
e.g.
?point=51.131,12.414&point=48.224,3.867
So there are two "point" entries, each containing two data items in comma-separated format.
Whereas you've got four separate "point[x][y]" variables in your querystring output. Your dd output suggests that request()->input('point1') and request()->input('point2') are themselves arrays. So what you've got is an array consisting of two further arrays, rather than a flat structure.
I think you need to write it like this:
'point' => [request()->input('point1')[0].",".request()->input('point1')[1], request()->input('point2')[0].","request()->input('point2')[1]]
Try that, I think it should work, or at least get you a lot closer to where you need to be.
Related
$client = new Client([
'base_uri' => 'http://localhost',
]);
$response = $client->request('POST', '/API/customerOrder/createOrder.php', [
'json' =>[
'SKU_QUANTITY' => [9,7,8],// we send the array of 3 elements to specific ID array.
'CUSTOMER_ID'=>[12,23,34] // This is the array which contain ID.
]
]);
Welcome to Stackoverflow!
If you are using Laravel and consuming the internal APIs using Guzzle, your request seems correct, however the data that you are posting to the endpoint could be incorrect. Here is an example of how it should be:
use Illuminate\Support\Facades\Http;
$response = Http::post('http://example.com/users', [
'name' => 'Steve',
'role' => 'Network Administrator',
]);
In your case, the request would be:
$data = [
'SKU_QUANTITY' => [9,7,8],
'CUSTOMER_ID'=>[12,23,34],
];
$response = Http::post('/API/customerOrder/createOrder.php', $data);
And in the API route that handles your request, you can get the data as follow:
$customerIdsArray = $request->get('CUSTOMER_ID');
//to get first element of the customer array you would use:
$Id1 = $customerIdsArray[0];
You could iterate the array and process the IDs as per your requirement.
Podio's API documentation differs from podio-php's when it comes to creating new Items.
Based on Podio's tutorial, I would have to format each value according to its type, whereas podio-php describes using PodioItemFieldCollection to handle that for you. I prefer the latter option, but I keep getting this error:
Invalid value "1" (string): Not a valid option
I don't see much difference in my code versus the example given by podio-php. What's causing this error?
$fields = new PodioItemFieldCollection(array(
new PodioTextItemField(array("external_id" => "my-text-field", "values" => "FooBar")),
new PodioProgressItemField(array("external_id" => "my-number-field", "values" => 75))
));
$atts = array(
'app' => new PodioApp($app_id),
'fields' => $fields
);
$item = new PodioItem($atts);
No errors caught up to here. But when I try to save...
$response = $item->save();
Invalid value "1" (string): Not a valid option
The $app_id was being passed in as a string. I've had this issue now with a few different ID values returned in an API response. I explicitly cast the value as an integer and the error went away:
$atts = array(
'app' => new PodioApp((int)$app_id),
'fields' => $fields
);
I am having the hardest time figuring out how to properly format a graphql api mutation POST request in php.
If I hard code the string and use it as the data in my POST request it works like this:
'{"query":"mutation{addPlay(input: {title: \"two\"}){ properties { title } } }"}'
But if I have a php array of the input values:
$test_data = array(
'title' => 'two'
);
I can't seem to format it correctly. json_encode also puts double quotes around the keys which graphql is rejecting with the error Syntax Error GraphQL request (1:26) Expected Name, found String.
I ultimately need a solution that will convert a larger more complex array to something usable.
Reformatting the query allowed me to use JSON directly.
So my new query looks like this:
$test_data = array(
'title' => 'two'
);
$request_data = array(
'query' => 'mutation ($input: PlayInput) { addPlay(input: $input) { properties { title } }}',
'variables' => array(
'input' => $test_data,
),
);
$request_data_json = json_encode($request_data);
Then the $request_data_json is used in a POST http request.
I using Phalcon PHP as PHP MVC Framework with MongoDB.
I can find object according with some criteria:
$user = User::findFirst(array(array('username' => $login, 'email'=> $login)));
As you can note, this request will return me the record according logical AND operator between conditions. I need to form request that will return result according with OR operator between conditions.
The problem also is that I'm using MongoDB, so, as I can suppose, I can't write PHQL request manually.
Just a matter of mangling PHP arrays
$user = User::findFirst( array(
'$or' => array(
array( 'username' => $login),
array( 'email' => $login)
)
));
So not only do I show the answer but also how my totals non PHP mind solves this problem:
$result = '{ "$or": [ { "username": "login" }, { "email": "login" } ] }';
echo var_dump( json_decode( $result ) );
$test = array(
'$or' => array(
array( 'username' => 'login'), array( 'email' => 'login')
)
);
echo json_encode( $test ) ."\n"
So in just a few lines we converted and proved. So since you knew the JSON from either the manual page or reading another question on SO, just convert it. And it's one of the reasons I submit the valid JSON in responses here, is so that the logic can be translated into just about any language implementation.
You can pass column names as string in first param:
$user = User::findFirst('username = "'.$login.'" OR email = "'.$login.'"');
$result = '{ "$or": [ { "username": "login" }, { "email": "login" } ] }';
User::findFirst(array(json_decode($query,true)));
$result is the exact json which can be used to trigger queries in mongodb command line
json_decode with 2nd parameter true will output the array style format of JSON
I have a little REST API in my project. And ofcourse i use json as my return data to work with.
I am using symfony in the backend and angularJs in the frontend. At the moment i convert my entity to json by looping true my result and filling an data array to return as json.
EXAMPLE:
public function getAction($id)
{
$em = $this->getDoctrine()->getManager();
$warehouseId = $this->get('session')->get('warehouse');
$warehouse = $em->getRepository('BubbleMainBundle:Warehouse')->find($warehouseId);
$trip = $em->getRepository('BubbleMainBundle:Trip')->find($id);
$data = array(
'id' => $trip->getId(),
'driver' => $trip->getDriver(),
'status' => $trip->getStatus(),
'date' => $trip->getPlanningDate()->format('Y-m-d')
);
if ( count($trip->getStops()) > 0 ) {
foreach($trip->getStops() as $stop)
{
$data['assignedStops'][] = array(
'id' => $stop->getId(),
'status' => $stop->getStatus(),
'date' => $stop->getDeliveryDate()->format('Y-m-d'),
'sort' => $stop->getSort(),
'company' => array(
'name' => $stop->getToCompany()->getName(),
'lat' => $stop->getToCompany()->getLat(),
'lng' => $stop->getToCompany()->getLng(),
'address' => $stop->getToCompany()->getAddress(),
'zip' => $stop->getToCompany()->getZip()
),
);
}
} else {
$data['assignedStops'][] = '';
}
$response = new jsonResponse();
$response->setData($data);
return $response;
}
This works. But sometimes i have have (google chrome timeline) waiting responses of 6 seconds for just a simple query and json response.
Is looping true the entity to much? Or do i need another approach for converting my entities to json format?
thx anthony,
If you are using PHP 5.4 or above then considering using the JsonSerializable interface with your entities:
http://www.php.net/manual/en/class.jsonserializable.php
This will allow you to control how your entities are converted to JSON which will allow you to call json_encode directly on your entities without having to loop through and convert them to arrays.
As for the performance issue you'd need to profile your script to find out where the performance bottleneck is. From looking at your code one potential issue that you might want to look into is to make sure you are fetching all the data in your original query (i.e stops and companies) and you are not executing additional queries in the foreach loop to fetch the missing stop and company data.
I recommend you (since you are using Symfony2 as a backend and you need an API) to definitely try out this bundle... It's easy to use and to setup and as an extra you can also generate a nice documentation for it.
It will speed up your development and code.