Override/change name of fields in JSON response in API Platform - api

I am working on an API Platform 3 (Symfony 6) app.
In my JSON response, I have the following :
{
...
"totalItems": 7065,
"itemsPerPage": 10,
...
}
Is it possible to change the config so that I get :
{
...
"total_items": 7065,
"page_size": 10,
...
}
So basically I want to rename these fields, in the response I get. Is it possible ?

If your question is about parameter names for pagination only, so then you can just execute bin/console debug:config api_platform and you will see available config parameters (documentation) under api_platform.collection.pagination:
collection:
pagination:
page_parameter_name: page
items_per_page_parameter_name: perPage
enabled: true
partial: false
client_enabled: false
client_items_per_page: false
client_partial: false
items_per_page: 30
maximum_items_per_page: null
enabled_parameter_name: pagination
partial_parameter_name: partial
Hope you will find what you want. Anyway, you can always to find the place where this piece is serialized and try to decorate/override it.
Otherwise, if you want to change the name of some another parameter from api resource you can use SerializedName() attribute on this property

The custom normalizer is the solution to this question.
A custom event listener is also a solution but it is not GraphQL friendly.

Related

Autodesk PDF Extension - Preventing page in query string override

I'm currently looking to implement pagination within the ForgeViewer PDF Extenstion, in the documentation there's a note that 'page' in the querystring will override any value passed to load model. I wondered if this was configurable or we were able to prevent this.
// URL parameter page will override value passed to loadModel
viewer.loadModel(‘path/to/file.pdf’, { page: 1 });
This is causing us a few issues as we use 'page' for other purposes and we'll have to rework quite a bit to rename our current page querystring which we're using for paginating tables.
That's correct. If you look inside the PDF extension's code (https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/extensions/PDF/PDF.js) then you'll find that this behaviour is hardcoded unfortunately 😞
I can think of two workarounds:
a) Use a URL param other than page - e.g. sheet?
b) Overwrite the current URL so that the page number will become what you need
// Original URL is: http://127.0.0.1:5500/index.html?page=2
// we change it to page=1
// This should change the URL content without a reload
history.pushState('', '', 'index.html?page=1');
viewer.loadModel("AutoCAD_Sample_Part1.pdf", {}, (model) => {
You could also achieve the same like this:
viewer.loadExtension('Autodesk.PDF').then(function(ext) {
// Original URL is: http://127.0.0.1:5500/index.html?page=2
// we change it to page=1
viewer.loadModel("AutoCAD_Sample_Part1.pdf", {}, (model) => {
ext.hyperlinkTracker.changePage(1)

How to change keys lable of yii2 advanced API response

I have created API module in my yii2 advanced application and also added HttpBearerAuth in controller file and it is working.
On Unauthorized I'm getting below response :
{"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401,"type":"yii\\web\\UnauthorizedHttpException"}
I want to change key label of this response like below :
{"error":"Unauthorized","errorMessage":"Your request was made with invalid credentials.","code":0,"status":401}
How do I update these keys?
Attach an event handler to yii\web\Response::EVENT_BEFORE_SEND and examine the $data attribute of the yii\web\Response class. Not sure, but guess you'll find an array where the keys are exactly those that you want to change.
You just need to filter out the responses you want to handle (eg everything except status codes 200 & 201).
Maybe something like this... probably bugs included :-)
Event::on(yii\web\Response::className(), yii\web\Response::EVENT_BEFORE_SEND, function ($event) {
if (Yii::$app->response->getStatusCode() > 201) {
if (isset(Yii::$app->response->data['name']) {
Yii::$app->response->data['error'] = Yii::$app->response->data['name'];
unset(Yii::$app->response->data['name']);
}
}
});

Generate Url from virtual field or from value of another field

I would like to generate a Url in a list in keystoneJS. I prefer that the url not be stored in mongo.
Attempted:
Virtual field: works, but will not generate raw HTML for the href.
Types.Url: I get the href format, but I need a value from another field in my model, so it generates the url with undefined.. Example:
{ type: Types.Url, label: "Link", default: "[http://www.stackoverflow.com/ask?id=][1]" + this._id }
Any help on how to pull this off would be much appreciated.
For your second point, this._id is not available when adding fields to the model, hence why you're getting undefined.
Instead, try using a pre-save hook on your model:
yourModel.pre('save', function(next) {
this.link = "[http://www.stackoverflow.com/ask?id=][1]" + this._id;
next();
}
I'm not quite sure if you're trying to just generate a link in this way every time, or if the user should also be able to add their own link. If the later, you'll need to check if the link has been filled in in the pre-save hook.
I hope that helps and sorry it took so long to get an answer on this!

WooCommerce REST API Custom Fields

Is it possible to access custom fields for orders, products, customers via WooCommerce REST API? If not natively, then what plugins or workarounds or hacks are out there that work? Thanks!
Answering my own question:
It is possible using the following: (using v3 legacy API)
To send custom fields back to the server:
(For Orders)
{
"order_meta": {
"key": "value"
}
}
To retrieve custom fields from server use this filter with your end point:
http://www.example.com/wc-api/v3/orders?filter[meta]=true
This works for Products as well.
As mentioned in the comment after WooCommerce creates an order via the API it will fire woocommerce_api_create_order hook, you can make use of it.
Add the following code to your theme's functions.php file
add_action( 'woocommerce_api_create_order', 'my_woocommerce_api_create_order', 10, 2);
function my_woocommerce_api_create_order( $order_id, $data ) {
// $data contains the data was posted, add code to extract the required
// fields and process it as required
}
Similarly look at the code in plugins/woocommerce/includes/api/*.php files, find the suitable action or filter hook for the end point and use it.
SIMPLE SOLUTION THAT WORKED FOR ME (using REST API REQUEST):
URL: https:///wp-json/wc/v3/orders/1234
METHOD: PUT
BODY:
{
"status": "completed",
"meta_data": [{
"key": "is_web_server_handled",
"value": "1"
}]
}

EmberJS Route to 'single' getting JSONP

I'm having trouble with EmberJS to create a single view to posts based on the ID, but not the ID of the array, I actually have a ID that comes with the json I got from Tumblr API.
So the ID is something like '54930292'.
Next I try to use this ID to do another jsonp to get the post for this id, it works if you open the api and put the id, and actually if you open the single url with the ID on it, works too, the problem is:
When, on the front page for example, I click on a link to go to the single, it returns me nothing and raise a error.
But if you refresh the page you get the content.
Don't know how to fix and appreciate some help :(
I put online the code: http://tkrp.net/tumblr_test/
The error you were getting was because the SingleRoute was being generated as an ArrayController but the json response was not an Array.
App.SingleController = Ember.ObjectController.extend({
});
Further note that the model hook is not fired when using linkTo and other helpers. This because Ember assumes that if you linked to a model, the model is assumed to be as specified, and it directly calls setupController with that model. In your case, you need to still load the individual post. I added the setupController to the route to do this.
App.SingleRoute = Ember.Route.extend({
model: function(params) {
return App.TKRPTumblr.find(params.id);
},
setupController: function(controller, id) {
App.TKRPTumblr.find(id)
.then(function(data) {
controller.set('content', data.response);
});
}
});
I changed the single post template a bit to reflect how the json response. One final change I made was to directly return the $.ajax. Ember understands jQuery promises directly, so you don't need to do any parsing.
Here is the updated jsbin.
I modified: http://jsbin.com/okezum/6/edit
Did this to "fix" the refresh single page error:
setupController: function(controller, id) {
if(typeof id === 'object'){
controller.set('content', id.response);
}else{
App.TKRPTumblr.find(id)
.then(function(data) {
controller.set('content', data.response);
});
}
}
modified the setupController, since I was getting a object when refreshing the page and a number when clicking the linkTo
Dont know if it's the best way to do that :s