Podio API JS - Update relationship field of a Item - podio

Using NodeJS, I am trying to update relationship field which link to another app (contacts-leads). I have try all combination but still getting error. I think I have the necessary data to post, app_id, item_id, external_id..etc. I need help with forming JSON structure.
p.request('put','item/<Item_Id>/value', data)
var data {....}
app_id:'<app_id>'
value:'<value>' (value is the app_item_id of the link to application; that is the number in URL)
app_item_id: '<app_item_id>'
external_id:'<external_id>'
I was able to update non-relationship field without problem.
Thanks

Well, going to answer my own question. That will work for single app link, not sure about multiple ones.
data = {
"<external_id>": {
"apps": [{"app_id": <app_id>}],
"value: <app_item_id>
}
}

Related

How to attach multiple parameters to an API request?

I built my own simple REST API with Express and now I'm consuming it from my client (Vue.js)
So in my page I access all the data from this endpoint: GET /api/books, and it works fine
Now I also have a "sort by" button where I want to get the data by the latest entries. I don't know if that's a good way or if I have to handle this in the backend but what I do is calling the same endpoint which is GET /api/books and sorting the data to get them the right way
For ex:
sortByLatest() {
axios
.get("/api/books")
.then(res => {
const books = res.data;
const sortedBooks = books.sort((a, b) => b.createdAt > a.createdAt ? 1 : -1
);
this.books = sortedBooks;
})
// catch block
}
I do that for everything. If I need a limited number of results or a specific property from the data I have to write some logic in the axios .then block to sort or filter what I want. Is this bad practice?
But that's not my actual problem
My problem is, in addition of sorting by the latest entries, I also want to filter the results by a specific property. The problem is when I click the A button it's gonna filter the books by a specific property, and when I click the B button it's gonna sort them buy the latest entries, but not both at the same time!
And what if I want additionnal things like limit the number of results to 10, filter by other properties etc... I want to be able to create requests that ask all those things at once. How can I do that? Do I have to build that in the backend?
I saw some websites using url parameters to filter stuff, like /genre=horror&sort=latest, is that the key of doing it?
Thank you for your time

API formation for side loading only required associated data to ember data

Please check my previous question
EMBER JS - Fetch associated model data from back-end only when required
Related to the above question I need help on API formation in ruby on rails(JSON format: jsonapi.org)
how to form the API for sideloading only students.records and link with data already available in ember-data store (school and students)
based on the comments in the other question, I think you're wanting something like
GET /api/students?include=records
But you need that filtered to a school, which is where application-specific code can come in, as { json:api } does not dictate how filtering should happen
but, I've used this: https://github.com/activerecord-hackery/ransack with much success
So, your new query would be something like:
GET /api/students?include=records&q[school_id_eq]=1
to get all students and their records for the school with id 1
and then to make this query in ember:
store.query('student', {
include: 'records',
q: {
['school_id_eq']: 1
}
});
hope this helps

Unable to use Ember data with JSONAPI and fragments to support nested JSON data

Overview
I'm using Ember data and have a JSONAPI. Everything works fine until I have a more complex object (let's say an invoice for a generic concept) with an array of items called lineEntries. The line entries are not mapped directly to a table so need to be stored as raw JSON object data. The line entry model also contains default and computed values. I wish to store the list data as a JSON object and then when loaded back from the store that I can manipulate it as normal in Ember as an array of my model.
What I've tried
I've looked at and tried several approaches, the best appear to be (open to suggestions here!):
Fragments
Replace problem models with fragments
I've tried making the line entry model a fragment and then referencing the fragment on the invoice model as a fragmentArray. Line entries add to the array as normal but default values don't work (should they?). It creates the object and I can store it in the backend but when I return it, it fails with either a normalisation issue or a serialiser issue. Can anyone state the format the data be returned in? It's confusing as normalising the data seems to require JSONAPI but the fragment requires JSON serialiser. I've tried several combinations but no luck so far. My line entries don't have actual ids as the data is saved and loaded as a block. Is this an issue?
DS.EmbeddedRecordsMixin
Although not supported in JSONAPI, it sounds possible to use JSONAPI and then switch to JSONSerializer or RESTSerializer for the problem models. If this is possible could someone give me a working example and the JSON format that should be returned by the API? I have header authorisation and other such data so would I still be able to set this at the application level for all request not using my JSONAPI?
Ember-data-save-relationships
I found an add on here that provides an add on to do this. It seems more involved than the other approaches but when I've tried this I can send the data up by setting a the data as embedded. Great! But although it saves it doesn't unwrap it correct and I'm back with the same issues.
Custom serialiser
Replace the models serialiser with something that takes the data and sends it as plain JSON data and then deserialises back into something Ember can use. This sounds similar to the above but I do the heavy lifting. The only reason to do this is because all examples for the above solutions are quite light and don't really show how to set this up with an actual JSONAPI set up that would need it.
Where I am and what I need
Basically all approaches lead to saving the JSON fine but the return JSON from the server not being the correct format or the deserialisation failing but it's unclear what it should be or what needs to change without breaking the existing JSONAPI models that work fine.
If anyone know the format for return API data it may resolve this. I've tried JSONAPI with lineEntries returning the same format as it saved. I've tried placing relationship sections like the add on suggested and I've also tried placing relationship only data against the entries and an include section with all the references. Any help on this would be great as I've learned a lot through this but deadlines a looming and I can't see a viable solution that doesn't break as much as it fixes.
If you are looking for return format for relational data from the API server you need to make sure of the following:
Make sure the relationship is defined in the ember model
Return all successes with a status code of 200
From there you need to make sure you return relational data correctly. If you've set the ember model for the relationship to {async: true} you need only return the id of the relational model - which should also be defined in ember. If you do not set {async: true}, ember expects all relational data to be included.
return data with relationships in JSON API specification
Example:
models\unicorn.js in ember:
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user', {async: true}),
staticrace: DS.belongsTo('staticrace',{async: true}),
unicornName: DS.attr('string'),
unicornLevel: DS.attr('number'),
experience: DS.attr('number'),
hatchesAt: DS.attr('number'),
isHatched: DS.attr('boolean'),
raceEndsAt: DS.attr('number'),
isRacing: DS.attr('boolean'),
});
in routes\unicorns.js on the api server on GET/:id:
var jsonObject = {
"data": {
"type": "unicorn",
"id": unicorn.dataValues.id,
"attributes": {
"unicorn-name" : unicorn.dataValues.unicornName,
"unicorn-level" : unicorn.dataValues.unicornLevel,
"experience" : unicorn.dataValues.experience,
"hatches-at" : unicorn.dataValues.hatchesAt,
"is-hatched" : unicorn.dataValues.isHatched,
"raceEndsAt" : unicorn.dataValues.raceEndsAt,
"isRacing" : unicorn.dataValues.isRacing
},
"relationships": {
"staticrace": {
"data": {"type": "staticrace", "id" : unicorn.dataValues.staticRaceId}
},
"user":{
"data": {"type": "user", "id" : unicorn.dataValues.userId}
}
}
}
}
res.status(200).json(jsonObject);
In ember, you can call this by chaining model functions. For example when this unicorn goes to race in controllers\unicornracer.js:
raceUnicorn() {
if (this.get('unicornId') === '') {return false}
else {
return this.store.findRecord('unicorn', this.get('unicornId', { backgroundReload: false})).then(unicorn => {
return this.store.findRecord('staticrace', this.get('raceId')).then(staticrace => {
if (unicorn.getProperties('unicornLevel').unicornLevel >= staticrace.getProperties('raceMinimumLevel').raceMinimumLevel) {
unicorn.set('isRacing', true);
unicorn.set('staticrace', staticrace);
unicorn.set('raceEndsAt', Math.floor(Date.now()/1000) + staticrace.get('duration'))
this.set('unicornId', '');
return unicorn.save();
}
else {return false;}
});
});
}
}
The above code sends a PATCH to the api server route unicorns/:id
Final note about GET,POST,DELETE,PATCH:
GET assumes you are getting ALL of the information associated with a model (the example above shows a GET response). This is associated with model.findRecord (GET/:id)(expects one record), model.findAll(GET/)(expects an array of records), model.query(GET/?query=&string=)(expects an array of records), model.queryRecord(GET/?query=&string=)(expects one record)
POST assumes you at least return at least what you POST to the api server from ember , but can also return additional information you created on the apiServer side such as createdAt dates. If the data returned is different from what you used to create the model, it'll update the created model with the returned information. This is associated with model.createRecord(POST/)(expects one record).
DELETE assumes you return the type, and the id of the deleted object, not data or relationships. This is associated with model.deleteRecord(DELETE/:id)(expects one record).
PATCH assumes you return at least what information was changed. If you only change one field, for instance in my unicorn model, the unicornName, it would only PATCH the following:
{
data: {
"type":"unicorn",
"id": req.params.id,
"attributes": {
"unicorn-name" : "This is a new name!"
}
}
}
So it only expects a returned response of at least that, but like POST, you can return other changed items!
I hope this answers your questions about the JSON API adapter. Most of this information was originally gleamed by reading over the specification at http://jsonapi.org/format/ and the ember implementation documentation at https://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html

Right way to dynamically update view in Angular

What is the right way to updated the Model in the view, say after a successful API POST. I've a textarea, something like in a Twitter, where a user can enter text and post. The entered text must show up soon after it is posted successfully.
How to achieve this? Should I make another call to get the posts separately or is there any other way to do this?
My Code looks like
feedsResolve.getFeeds().then(function(feeds){
$scope.feeds = feeds;
}
where feedsResolve is a service returning a promise
$scope.postFeed = function(){
var postObj = Restangular.all('posts');
postObj.post( $scope.feed.text ).then(function(res){
//res contains only the new feed id
})
}
How do I update the $scope.feeds in the view?
I assume you are posting a new post and that generally posts look like:
{
id: 42,
text: 'This is my text'
}
In this case you can do something like:
$scope.postFeed = function(){
var postObj = Restangular.all('posts');
var feedText = $scope.feed.text;
postObj.post( feedText ).then(function(res){
$scope.feeds.push({ id: res.id, text: feedText});
})
};
A better practice when writing restful service though is to just have your POST return an actual JSON object with the new feed that was added (not just the id). If that were the case you could just add it to your feeds array.
If your JSON object is complex, this practice is the most common an easiest way to handle this without needing extra requests to the server. Since you already are on the server, and you've likely already created the object (in order to be able to insert it into the database), all you have to do is serialize it back out to the HTTP response. This adds little to no overhead and gives the client all the information it needs to effortlessly update.

GitHub API (v3): Order tags by creation date

I ran into a problem / question while using the GitHub API.
I need a list of all tags created after a single tag. The only way to do this, is to compare the tags by date. However, the results from the API aren't ordered by date:
Result from the API (rails repository example):
Results from the webinterface:
What i did expect is a list ordered by date. However, as you can see in the pictures: the API is returning v4.0.0rc1 & v4.0.0rc2 before the release of v4.0.0, while 4.0.0 is released after the release candidates. There isn't even a creation / commit date to order at server side.
The releases API isn't a solution either. This API is only returning releases created by Github, not the releases created by tags.
Is there any way to order the tags by date?
Thanks in advance!
Ruben
The Repositories API currently returns tags in the order they would be returned by the "git tag" command, which means they are alphabetically sorted.
The problem with sorting tags chronologically in Git is that there are two types of tags, lightweight and annotated), and for the lightweight type Git doesn't store the creation date.
The Releases/Tags UI currently sorts tags chronologically by the date of the commit to which the tag points to. This again isn't the date on which the tag itself was created, but it does establish a chronological order of things.
Adding this alternative sorting option to the API is on our feature request list.
With GraphQL API v4, we can now filter tags by commit date with field: TAG_COMMIT_DATE inside orderBy. The following will perform ascending sort of tags by commit date :
{
repository(owner: "rails", name: "rails") {
refs(refPrefix: "refs/tags/", last: 100, orderBy: {field: TAG_COMMIT_DATE, direction: ASC}) {
edges {
node {
name
target {
oid
... on Tag {
message
commitUrl
tagger {
name
email
date
}
}
}
}
}
}
}
}
Test it in the explorer
Here, the tagger field inside target will only be filled for annotated tag & will be empty for lightweight tags.
As date property in tagger gives the creation date of the tag (for annotated tag only), it's possible to filter by creation date on the client side easily (without having to retrieve all the tags 1 by 1)
Note that available options for orderBy.field at this time are TAG_COMMIT_DATE & ALPHABETICAL (no TAG_CREATION_DATE)
Edit: This is now possible using the GitHub GraphQL API.
As workaround, there is a node module for this,
which basically fetches the commit details of each tag:
github-api-tags-full
> npm install github-api-tags-full github moment
var GitHubApi = require('github'),
moment = require('moment'),
githubTags = require('github-api-tags-full');
var github = new GitHubApi({
version: '3.0.0'
});
githubTags({ user: 'golang', repo: 'go' }, github)
.then(function(tags) {
var tagsSorted = tags.sort(byAuthorDateAsc).reverse(); // descending
console.log(tagsSorted); // prints the array of tags sorted by their creation date
});
var byAuthorDateAsc = function(tagA, tagB) {
return githubCompareDates(
tagA.commit.author.date,
tagB.commit.author.date
);
};
var githubCompareDates = function(dateStrA, dateStrB) {
return moment(dateStrA).diff(dateStrB);
};
With best regards
You can use the Git References API.
This can return also all the tags matching a certain prefix.
In you case, you probably want something like:
https://api.github.com/repos/rails/rails/git/matching-refs/tags/v
Or in the case of a monorepo:
https://api.github.com/repos/grafana/loki/git/matching-refs/tags/helm-loki-
Downsides:
sorting: the results are sorted in increasing semver order and you will get the oldest first.
you don't get much info about each tag and you might have to parse the versions out of the ref name/path
Upside
you get all the ref/tags that match (i.e. no pagination, until GitHub decides to remove/optimise this :) )
you can use it to filter out tags in a monorepo (that most probably tag release components with prefixed tags)