I'm using Laravel/PHP to output some JSON for Ember to pick up.... a couple of things here.
First, my PHP looks like this (is there another way to send the data)
return Response::json([
'articles' => $articles->toArray()
], $statusCode);
This is what I am used to doing.
foreach($articles as $article) {
$response['articles'][] = [
'id' => $article->id,
'body' => $article->body,
'title' => $article->title
];
}
return Response::json([
'articles' => $articles->toArray()
], $statusCode);
The first PHP snippet works fine, but the second does not. I get all kinds of errors about resource types by Ember.
Next question is for Ember heads. Right now I am getting everything working with RESTAdapter but should I be using JSONAPIAdapter instead? When I try to get it working with JSONAPIAdapter and JSONAPISerializer I get this error
One or more of the following keys must be present: \"data\",
\"errors\", \"meta
. I can get that error to go away but then I get an error about an undefined type or an unknown resource.
Its not mandatory to use JSONAPIAdapter, but if you have control over the API then you can very well using it. API response should follow the format (http://jsonapi.org/format/)
Sample format for single resource object,
{
"data": {
"type": "articles",
"id": "1",
"attributes": {
// ... this article's attributes
}
}
}
Sample format for multiple resource objects,
{
"data": [{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON API paints my bikeshed!"
}
}, {
"type": "articles",
"id": "2",
"attributes": {
"title": "Rails is Omakase"
}
}]
}
Related
I'm posting data to my API endpoint. it's simple JSON data. But I'm getting error 404 when posting data as raw JSON but if I post the same data at the same endpoint as raw text its works.
working as raw text
getting error 404 as raw JSON
<?php
var_dump(http_response_code());
echo "hello";
var_dump($_POST);
echo file_get_contents("php://input");
I have removed all code from the API end point and just trying to print post data.
Sample JSON :
{
"object": "whatsapp_business_account",
"entry": [
{
"id": "456",
"changes": [
{
"value": {
"messaging_product": "whatsapp",
"metadata": {
"display_phone_number": "123456789",
"phone_number_id": 123456789
},
"contacts": [
{
"profile": {
"name": "NAME"
},
"wa_id": 123456789
}
],
"messages": [
{
"from": 123456789,
"id": "wamid.ID",
"timestamp": 123456789,
"text": {
"body": "MESSAGE_BODY"
},
"type": "text"
}
]
},
"field": "messages"
}
]
}
]
}
I have checked JSON and it's a valid JSON. no special character but still unable to solve this issue.
One more thing its working on my local machine under XAMPP but not on Linux shared server.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 months ago.
I've been trying to find ways to print the individual data but can't seem to figured out where I'm going wrong.
I started with this but I get no results. Before this I tried nesting loops but also got nowhere either.
$data = curl_exec($ch);
$d = json_decode($data, true);
foreach($d as $k=>$v){
echo $v['value']['displayName'];
}
Then I tried the following with only got me some of the results. I'm not sure where I'm going wrong with this.
foreach(json_decode($data,true) as $d){
foreach($d as $k=>$v){
foreach($v as $kk=>$vv){
echo $kk.$vv;
}
}
}
The JSON looks like the following:
{
"value": [
{
"id": "",
"name": "",
"etag": "",
"type": "Microsoft.SecurityInsights/alertRules",
"kind": "Scheduled",
"properties": {
"incidentConfiguration": {
"createIncident": true,
"groupingConfiguration": {
"enabled": false,
"reopenClosedIncident": false,
"lookbackDuration": "PT5M",
"matchingMethod": "AllEntities",
"groupByEntities": [],
"groupByAlertDetails": null,
"groupByCustomDetails": null
}
},
"entityMappings": [
{
"entityType": "Account",
"fieldMappings": [
{
"identifier": "FullName",
"columnName": "AccountCustomEntity"
}
]
},
{
"entityType": "IP",
"fieldMappings": [
{
"identifier": "Address",
"columnName": "IPCustomEntity"
}
]
}
],
"queryFrequency": "P1D",
"queryPeriod": "P1D",
"triggerOperator": "GreaterThan",
"triggerThreshold": 0,
"severity": "Medium",
"query": "",
"suppressionDuration": "PT1H",
"suppressionEnabled": false,
"tactics": [
"Reconnaissance",
"Discovery"
],
"displayName": "MFA disabled for a user",
"enabled": true,
"description": "Multi-Factor Authentication (MFA) helps prevent credential compromise. This alert identifies when an attempt has been made to diable MFA for a user ",
"alertRuleTemplateName": null,
"lastModifiedUtc": "2022-11-14T02:20:28.8027697Z"
}
},
...
...
...
Here is how you can get the display name without a loop. Notice that the 0 is the key value of the array since it doesn't have a name.
We start from the value, and we move one layer deeper by selecting the first array 0. Now we need to select the properties and finally, we can get the displayName from there.
$displayName = $d["value"][0]["properties"]["displayName"];
echo($displayName);
/*
Here is a quick demonstration:
value:
{
0:
{
...
properties:
{
...
displayName: [We made it!]
}
}
}
*/
And here is a very good post that explains this in more detail
How to decode multi-layers nested JSON String and display in PHP?
I use this repository hkarlstrom/openapi-validation-middleware to verify incoming and outgoing json requests and responses in my api build on php slim.
I want to rework the error output to another json format.
Currently it is, as example:
Error 400:
{
"message": "Request validation failed",
"errors": [
{
"name": "catalogus",
"code": "error_format",
"value": "",
"in": "query",
"type": "string",
"format": "uri"
}
]
}
I tried to catch this error so i can modify the repsonse like this:
$mw = new HKarlstrom\Middleware\OpenApiValidation(__DIR__.'/catalog_openapi.json');
$options = [
'validateRequest'=> false,
'exampleResponse' => true,
'beforeHandler' => function (\Psr\Http\Message\ServerRequestInterface $request, array $errors) : \Psr\Http\Message\ServerRequestInterface {
// Alter request modifiy the json reponse here !!!
echo "tadaaaa"; <- never outputted
return $request;
}
];
And finally in my route:
$app->get('/v1/dosomething[/{params:.*}]',\App\Action\DoSomething::class)->add($mw,$options);
But it never touches the before- or errorHandler.
Any ideas how to get this working?
I am doing some work with the Yahoo Gemini API that uses PHP. My current goal is requesting reports through it using Python code.
In PHP, you would create a request using these types of arguments appended to the request:
"fields": [
{ "field": "Ad ID" },
{ "field": "Day" },
{ "alias": "My dummy column", "value": "" },
{ "field": "Impressions" },
{ "field": "Ad Image URL", "alias": "url" }
],
No problem, I type the data and then convert it to a dictionary.
fields_to_include = [('field', 'Campaign ID'), ('field', 'Day'), ('field', 'Impressions'), ('field', 'Clicks'), ('field', 'CTR')]
fields_to_include = dict(fields_to_include)
filters_to_include = [('field', 'Advertiser ID'),('operator','='),('value', str(advertiser_id))]
filters_to_include = dict(filters_to_include)
I get this error:
TypeError: 'dict' object is not callable
All the other answers on this site do not seem to be similar to this. What is going wrong here?
You've previously named a variable 'dict', which has shadowed the dict built-in.
However, that code would not give you what you want; it produces a single dict, which only has one value (because you can't have multiple keys with the same name). What you want is a list of dicts.
I don't understand why you don't hard code it exactly as you did in PHP.
fields_to_include = [
{ "field": "Ad ID" },
{ "field": "Day" },
{ "alias": "My dummy column", "value": "" },
{ "field": "Impressions" },
{ "field": "Ad Image URL", "alias": "url" }
]
I'm trying to use Tumblrs API and when I visit the URL for the API I get this below
{
"meta": {
"status": 200
"msg": "OK",
},
"response": {
"blog": {
"title": "Ex-Sample",
"posts": 20,
"name": "example",
"url": "http://example.tumblr.com/",
"updated": 1327794725,
"description": "A sample document used to provide examples of the various [and <i>varying</i>] HTML tags Tumblr puts out. Quote, specifically, has a lot of variants.",
"ask": false
}
}
}
The URL is http://api.tumblr.com/v2/blog/example.tumblr.com/info?api_key=(APIKEY)
I'm trying to get what the "post" number is with that URL above. How would I do that in PHP and echo the number only out?.
That looks like a JSON string, so...
$msg = '{"meta" etc.....';
$data = json_decode($msg);
echo $data['meta']['response']['blog']['posts'];
You can use
var_dump($data);
to dump the entire response in a nicely formatted tree structure.