Podio - updating item field results in empty field [closed] - podio

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to update an item field value in Podio via AJAX request - I can make the requests successfully, but rather than updating the field value to the value passed in the request, the item field in Podio is simply emptied (as though updated to an empty value). Here's the call:
$.ajax({
type:'PUT',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth2 ' + response.access_token)
},
url:'https://api.podio.com/item/654321/value/12345',
data: JSON.stringify({'value': 'new_value'})
}).done(function(response){
console.log(response)
}).fail(function(error){
console.log(error)
})
But the result of this will be to simply erase the old field value. Close, but no cigar.
How should the data attribute be formatted for Podio to correctly update the field value?
(I understand that there are a number of Podio client libraries that can help with this, but they are not useful to us in our current situation - we need to handle this process via good ol' AJAX)

Got it - it was an easy fix, just had to set the contentType. Silly me.
$.ajax({
type:'PUT',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth2 ' + response.access_token)
},
contentType: 'application/json',
url:'https://api.podio.com/item/654321/value/12345',
data: JSON.stringify({'value': 'new_value'})
}).done(function(response){
console.log(response)
}).fail(function(error){
console.log(error)
})

Related

How can I get foreign exchange rates thru an API by using PHP or Ajax? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I need a foreign exchange rate API in PHP for my recent project, in which I need updates after 60 sec.I also need metals like Gold, Silver etc latest exchange rates. So anyone who can I guide me for a PHP endpoint providing latest exchange rates. Any help will be highly appreciated.
I'll strongly recommend you CurrencyFreaks API. It provides foreign currency exchange rate endpoint in multiple languages including PHP and Ajax. It's prominent features are:
Data is updated every 60 sec.
You can change the ‘Base’ currency.
It provides currency exchange rates for 179 currencies worldwide including currencies, metals (Gold, Silver, Palladium, Platinum), and cryptocurrencies.
Supported codes for the endpoints are Shell, Node.js, Java, Python,
PHP, Ruby, JS, C#, Go, C, Swift.
Here's the latest exchange rates endpoint using PHP:
setUrl('https://api.currencyfreaks.com/latest
?apikey=YOUR_APIKEY
&base=GBP
&symbols=EUR,USD,PKR,INR');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
'follow_redirects' => TRUE
));
try {
$response = $request->send();
if ($response->getStatus() == 200) {
echo $response->getBody();
}
else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
}
catch(HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
For Ajax:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.currencyfreaks.com/latest
?apikey=YOUR_APIKEY
&base=GBP
&symbols=EUR,USD,PKR,INR");
xhr.send();
You can also get foreign exchange rate endpoint in other programming languages from here: https://currencyfreaks.com/documentation.html#Latest
I hope this solution will help for your recent project.

GET request that triggers PATCH request (express) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
On my express server I have a script which retrieves items through scraping. I want to trigger this script once in a while and push the retrieved items into my database.
My first ideas was to create an endpoint in my API (e.g. /api/scrape-items). The problem is that it would be a GET request responsible for running the script, retrieving the items AND PATCH the items (update) my database. It doesn't seem right to let a GET request do all of that, especially to make a PATCH request, but I can't change the GET request to a POST request either because I have no body.
Can someone help me come up with a better approach? Thanks!
UPDATE: Example of triggering endpoint:
router.get('/scrape-items/', async (req, res) => {
try {
const resultFromScraping = await [
{ id: 1, data: 'updated data' },
{ id: 2, data: 'updated data' }
]
await Promise.all(
resultFromScraping.map(
async item =>
await axios.patch(
`/api/items/${item.id}`,
item.data
)
)
)
} catch (err) {
res.status(500).json({ message: err.message })
}
})
A POST request is perfectly acceptable for uploading content to a database. PATCH is usually reserved for when you are partially updating and item. So if you are just updating stuff in your database with this request, then don't hesitate to use PATCH. If you are completely replacing the resource in the database though (or you require the entire resource in the HTTP request, not just the modified stuff), then I'd recommend using PUT instead.
A GET request would be acceptable as well in this situation if you were returning data to the user.

Any tutorial about express.js and deepstream work together [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
All:
As title asked, I am pretty new to Express and Deepstream, I wonder how can I make them work together( Or they have to work separately? )?
In Deepstream guide section ( https://deepstream.io/tutorials/integrations/ )
It only provides how to connect Frontend and Persistence layer, but not too much about how to co-work with other REST API service( only one small section: https://deepstream.io/tutorials/integrations/other-http/, but not too much user cases)
Any tutorial/Example( simple case like authorized chat and friend chat list )?
Thanks
Deepstream can currently be passed a http server to initialize its websocket server. However this behavior is being deprecated in the very near future as we want to further optimize deepstream.io by moving it more into the c++ space, meaning the http server will be able to handle much many more concurrent connections at the expense of not being configurable.
In most cases you can build your entire application using a deepstream client. The combination of data-sync, events and rpcs means that as long as you aren't looking at doing actions such as binary uploads/transfers you can benefit from picking the best tool to accomplish a task.
For example, you can use RPCs when requiring classic request/response atomic operations:
ds.rpc.provide( 'add-numbers', function( data, response ) {
var result = data.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
})
response.send( result )
} )
ds.rpc.make( 'add-numbers', [ 1, 3 ], function( err, data ) {
console.log( 'result: ', data )
} )
which is similar to express:
app.post( '/add-two', function( req, res ) {
var result = req.body.data.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
})
res.send( result )
} )
Except deepstream would also manage concepts such as service discovery and load balancing for you and even allow clients the opportunity to become endpoints if wanted.
or use events:
ds.event.emit( 'score-changed', score++ )
ds.event.subscribe( 'score-changed', function( newScore ) {
console.log( `The score changed on: ${newScore}` )
} )
or model your application data and synchronize it across all clients using records:
var record = ds.record.getRecord( 'playerA' )
record.subscribe( 'score', function( newScore ) {
console.log( `Player A score has changed to: ${newScore}` );
} );
record.set( 'score', record.get('score')++ );
I hope that helps!

Best practice to batch update a collection in a REST Api call [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Hi I'm looking for best practices with API design to batch update a collection with an API call.
My collection has URL /api/v1/cars and I would like to update all the cars in the collection to add a timestamp of the current time.
{
data: [
{
manufacturer: 'Porsche',
timestamp: ...
},
{
manufacturer: 'BMW',
timestamp: ...
}
{
manufacturer: 'Peugeot',
timestamp: ...
}
}
I thought about a few options but I can't figure what is the best practice.
Should it be:
1/ Modelled as another resource such as POST api/v1/cars/updateTimestamp
2/ Passed as a query parameter: PUT api/v1/cars?updateTimestamp
3/ Pass in the body of the request:
POST api/v1/cars
{"operation":"Update timestamps"}
I'd like to emphasize that the whole processing should be done on the back-end and not passed by the client.
Same problem would happen for any complex processing that happens on the back end..
How could I keep the API RESTy in this case.
Thanks a lot for your help/any pointer to relevant ressources.
As there is no partial PUT defined in HTTP, you either need to send the whole entity for each resource to update or use some other operations.
POST
As POST is an all-purpose operation you can use it to create a short-living temporary resource at the server (which further does not even have to have an own URL). On receipt the server can update either all specified entries or all entries in general with some provided field-value combination (certain table alterering may be necessary though if the column is not yet know in relational databases)
A simple request may look like this:
POST /api/v1/cars/addAttributes HTTP/1.1
Host: example.org
Content-Length: 24
Content-Type: application/json
If-Match: "abc123"
{
"timestamp": "..."
}
This approach has the advantage that it could be sent to the server anytime, even without prior knowledge of the current state. This, however, also has the danger that certain entries get updated which shouldn't be affected. This can either be influenced by specifying an If-Match header, which points to a certain version-hash and is changed on every entity update, or by adding a certain restrictor to the JSON body which the server also has to understand.
PATCH
Similar to POST, which can literally send anything to the server, PATCH is intended for modification of resources. A single request explicitely may update multiple resources at once, however, the client needs to define the necessary steps to transform the resources from state A to state B. Therefore, the client also needs to have the latest state of the resource in order to successfully transform the resource to its newest state (-> ETag and If-Modified HTTP headers)
A JSON Patch request for the provided example may therefore look like this:
PATCH /api/v1/cars HTTP/1.1
Host: example.org
Content-Length: 215
Content-Type: application/json-patch+json
If-Match: "abc123"
[
{ "op": "add", "path": "/data/1", "value": [ "timestamp", "..." ] },
{ "op": "add", "path": "/data/2", "value": [ "timestamp", "..." ] },
{ "op": "add", "path": "/data/3", "value": [ "timestamp", "..." ] }
]
Where /data/1, /data/2 and /data/3 are the unique identifiers for the resources of Porsche, BMW and Peugeot.
PATCH specifies that a request has to be atomic which means that either all or none of the instructions succeed which also brings some transaction requirements to the table.
Discussion
As already mentioned, in POST requests you can literally send anything you want to the server at least as long as the server is capable of understanding what you are sending. It is therefore up to you how you design the request structure (and the server logic as well).
PATCH on the other hand, especially with JSON Patch defines some strict rules and predefined operations typically to traditional patching. The transaction requirement can be a burden but also a benefit. In addition to that, PATCH is not yet final and still in RFC though it is already widely available.
I would do a PUT to do an update operation. PUT is for updating objects, POST for creating. You could specify fields using query parameters.
POST /api/v1/cars > create new cars
PUT /api/v1/cars > update car based on id in the object. You could
also create a cars/:id route if you want to use the route without an
id to do an update on all car objects (which seems not to happen in
many applications).
GET /api/v1/cars > list all cars
GET /api/v1/cars/:id > list one car.
To answer your question. You want to update all car objects. In that case I would use the PUT /api/v1/cars and specify a /api/v1/cars/:id to do an update on one car, although I do not see why you want to implement this. If it is a one time operation, I would update all cars in the DB instead of creating an API route.

REST URIs for a Rule Engine (stateless engine) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need some guidance for designing REST URIs for a rule engine. There are a set of rules defined and stored in the back-end system in the form of XML files. These rules are grouped into various categories and a set of rules get executed based on the category specified by the user. The user passes a set of user selections/options and category as input to the rule engine. The rule engine executes the rules belonging to the category against the user selections/options. These are process/compute like operations which doesn't involve persistence of user state into the system. On a whole, the user state is not maintained in the rule engine... ie., a stateless rule engine.
I am trying to design REST APIs for rule engine execution (rule creation part is already taken care of):
The operation doesn't Create, Update, Delete any serve side resources.
The rules are executed against the user selections.
User selections can be complex (hierarchical structure) and it can't modeled as URI params.
Request your guidance is designing a REST URI pattern considering the above mentioned aspects.
To get a rules belonging to a category:
GET /rule_category/{id}
To process user selections in the context of rules (rule execution by rule engine):
POST /rule_engine
BODY to contain a JSON structure with rule category & user selections
Please provide your suggestions on the above URI design and any other possible URIs for the above mentioned use case. Should PUT/POST be used for rule execution URI?
EDIT 1: Adding the sample JSON/XML structure that encapsulates rule category and user selection info:
{
processdata:{
rulecategory:'ruleCat1',
userselections:{
userselection:[
{
item:'us1'
},
{
item:'us2'
},
{
item:'us3',
customselection:{
value:'cs1'
}
}
]
}
}
}
<ProcessData RuleCategory="ruleCat1">
<UserSelections>
<UserSelection Item="us1"/>
<UserSelection Item="us2"/>
<UserSelection Item="us3">
<CustomSelection Value="cs1"/>
</UserSelection>
</UserSelections>
REST is not Remote Procedure Call (RPC). REST is about Resources.
If you want to have a RESTful API that handles computations, model computations as resources.
Create a new computation resource
Request
POST /computations
Content-Type: application/json
{
// the selected rules etc.
}
Response
201 Created
Location: /computations/748A9FC0-B74E-11E4-8822-4D7FDD9DA696
where 748A9FC0-B74E-11E4-8822-4D7FDD9DA696 is the ID of this computation generated by the server.
Get the state of the computation
Request
GET /computations/748A9FC0-B74E-11E4-8822-4D7FDD9DA696
Response: still computing
200 OK
Content-Type: application/json
{
"id": "748A9FC0-B74E-11E4-8822-4D7FDD9DA696",
"data": { ... },
"state": "computing"
}
Response: finished
200 OK
Content-Type: application/json
{
"id": "748A9FC0-B74E-11E4-8822-4D7FDD9DA696",
"data": { ... },
"state": "finished",
"result": {
// details about the result
}
}
Your only options is POST in this case.
Be aware that REST has constraints e.g. uniform interface constraint, which includes HATEOAS. So you have to send links to your clients, which they can follow. In this case you will have hard time to explain the (machine) clients how to assemble the body of your request. A possible way to overcome this, is defining your application specific request media type.
So it is possible to solve this with REST, but I think you will work in this case much more than you would by an RPC. I agree with Lutz, you should not use REST by your Rule Engine if you don't have other resources which state are kept on the server.