Guest Cart Selected Variations not working in Etsy API - etsy

When using the addToGuestCart method of the guestCart API endpoint the selected_variations parameter isn't working. I've tried sending the post data in JSON format with selected_variations being set to an array
containing two variations retrieved from the getInventory endpoint. The API request gives a 200 HTTP response but doesn't return any data, and the item doesn't appear in the Etsy cart. Making the same API call without the selected_variations set works fine. Can you please advise the correct format for including selected_variations in a call to the addToGuestCart endpoint?

This worked for me:
const guestCart_data = {
url: "https://openapi.etsy.com/v2/guests/:guest_id/carts",
method: "POST",
data: {
guest_id: guestId,
listing_id: listingId,
quantity: 1,
selected_variations: `{"47626759898" : "55055453743", "513": "86877352060"}`
// selected_variations: `{"<property_id>" : "<value_ids>", "<property_id>": "<value_ids>"}`
},
};

Related

React-rails store POST request response

currently i used Ruby on Rails as my backend to serve API to my apps. And my front end i use React-rails gem (React.js) to get/post data and generate output. Both API and apps are on different server.
My problem here is, i cannot store response from POST request i made in react. How can i do so ? I am new in react btw.
What i want to do now is when user want to login the apps will POST request to API and get "auth_token" response. I want to store this "auth_token" response in header and access into dashboard. But i stuck now how can i store the auth_token ftw.
Below is my code for POST data :
var LoginBody = React.createClass(
{
handleClick() {
var username = this.refs.username.value;
var password = this.refs.password.value;
$.ajax({
url: 'http://localhost:3001/api/v1/users/central/signin?',
type: 'POST',
dataType: 'json',
data: { user_login:{email: username, password:password} },
success: (data) => {
this.setState({auth_token: data.auth_token});
}.bind(this),
});
},
getInitialState(){
return {
auth_token: []
}
},
If there's someone that could solve my problem and teach me how can i store in header in my apps i really appreciate it.
Just store them in local storage like:
localStorage.authToken = data.auth_token
And then whenever you need them in your future requests, just read as:
localStorage.authToken

How to retrieve Medium stories for a user from the API?

I'm trying to integrate Medium blogging into an app by showing some cards with posts images and links to the original Medium publication.
From Medium API docs I can see how to retrieve publications and create posts, but it doesn't mention retrieving posts. Is retrieving posts/stories for a user currently possible using the Medium's API?
The API is write-only and is not intended to retrieve posts (Medium staff told me)
You can simply use the RSS feed as such:
https://medium.com/feed/#your_profile
You can simply get the RSS feed via GET, then if you need it in JSON format just use a NPM module like rss-to-json and you're good to go.
Edit:
It is possible to make a request to the following URL and you will get the response. Unfortunately, the response is in RSS format which would require some parsing to JSON if needed.
https://medium.com/feed/#yourhandle
⚠️ The following approach is not applicable anymore as it is behind Cloudflare's DDoS protection.
If you planning to get it from the Client-side using JavaScript or jQuery or Angular, etc. then you need to build an API gateway or web service that serves your feed. In the case of PHP, RoR, or any server-side that should not be the case.
You can get it directly in JSON format as given beneath:
https://medium.com/#yourhandle/latest?format=json
In my case, I made a simple web service in the express app and host it over Heroku. React App hits the API exposed over Heroku and gets the data.
const MEDIUM_URL = "https://medium.com/#yourhandle/latest?format=json";
router.get("/posts", (req, res, next) => {
request.get(MEDIUM_URL, (err, apiRes, body) => {
if (!err && apiRes.statusCode === 200) {
let i = body.indexOf("{");
const data = body.substr(i);
res.send(data);
} else {
res.sendStatus(500).json(err);
}
});
});
Nowadays this URL:
https://medium.com/#username/latest?format=json
sits behind Cloudflare's DDoS protection service so instead of consistently being served your feed in JSON format, you will usually receive instead an HTML which is suppose to render a website to complete a reCAPTCHA and leaving you with no data from an API request.
And the following:
https://medium.com/feed/#username
has a limit of the latest 10 posts.
I'd suggest this free Cloudflare Worker that I made for this purpose. It works as a facade so you don't have to worry about neither how the posts are obtained from source, reCAPTCHAs or pagination.
Full article about it.
Live example. To fetch the following items add the query param ?next= with the value of the JSON field next which the API provides.
const MdFetch = async (name) => {
const res = await fetch(
`https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/${name}`
);
return await res.json();
};
const data = await MdFetch('#chawki726');
To get your posts as JSON objects
you can replace your user name instead of #USERNAME.
https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/#USERNAME
With that REST method you would do this: GET https://api.medium.com/v1/users/{{userId}}/publications and this would return the title, image, and the item's URL.
Further details: https://github.com/Medium/medium-api-docs#32-publications .
You can also add "?format=json" to the end of any URL on Medium and get useful data back.
Use this url, this url will give json format of posts
Replace studytact with your feed name
https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/studytact
I have built a basic function using AWS Lambda and AWS API Gateway if anyone is interested. A detailed explanation is found on this blog post here and the repository for the the Lambda function built with Node.js is found here on Github. Hopefully someone here finds it useful.
(Updating the JS Fiddle and the Clay function that explains it as we updated the function syntax to be cleaner)
I wrapped the Github package #mark-fasel was mentioning below into a Clay microservice that enables you to do exactly this:
Simplified Return Format: https://www.clay.run/services/nicoslepicos/medium-get-user-posts-new/code
I put together a little fiddle, since a user was asking how to use the endpoint in HTML to get the titles for their last 3 posts:
https://jsfiddle.net/h405m3ma/3/
You can call the API as:
curl -i -H "Content-Type: application/json" -X POST -d '{"username":"nicolaerusan"}' https://clay.run/services/nicoslepicos/medium-get-users-posts-simple
You can also use it easily in your node code using the clay-client npm package and just write:
Clay.run('nicoslepicos/medium-get-user-posts-new', {"profile":"profileValue"})
.then((result) => {
// Do what you want with returned result
console.log(result);
})
.catch((error) => {
console.log(error);
});
Hope that's helpful!
Check this One you will get all info about your own post........
mediumController.getBlogs = (req, res) => {
parser('https://medium.com/feed/#profileName', function (err, rss) {
if (err) {
console.log(err);
}
var stories = [];
for (var i = rss.length - 1; i >= 0; i--) {
var new_story = {};
new_story.title = rss[i].title;
new_story.description = rss[i].description;
new_story.date = rss[i].date;
new_story.link = rss[i].link;
new_story.author = rss[i].author;
new_story.comments = rss[i].comments;
stories.push(new_story);
}
console.log('stories:');
console.dir(stories);
res.json(200, {
Data: stories
})
});
}
I have created a custom REST API to retrieve the stats of a given post on Medium, all you need is to send a GET request to my custom API and you will retrieve the stats as a Json abject as follows:
Request :
curl https://endpoint/api/stats?story_url=THE_URL_OF_THE_MEDIUM_STORY
Response:
{
"claps": 78,
"comments": 1
}
The API responds within a reasonable response time (< 2 sec), you can find more about it in the following Medium article.

SAPUI5 oModel.create() - how to post data to the SAP backend?

I got a button where I want to post data to my SAP backend on press-method:
oCellBtnOtherchart.addContent(new sap.ui.commons.Button({
text : "Save",
press : function() {
var sServiceUrl = "/MyEntitSet('0001')";
var oModel = sap.ui.getCore().getModel();
console.log(oModel);
var oParameters = {
"email" : "a",
"lastname" : "b",
"firstname" : "c",
};
oModel.create(sServiceUrl, oParameters);
}
}));
My questions are:
In which method would this request end in backend? I expect MyEntitySet_CREATE_ENTITY()
Why doesnt it work, the error message is: HTTP request failed 405, Method Not Allowed
But why is it 405, is my Service URL Wrong? How do I Post data correctly to the SAP Backend?
SAP Troubleshooting Guide says: 405 Method Not Allowed
o The method specified in the Request-Line is not allowed for the resource
identified by the Request-URI. The response must include an Allow header
containing a list of valid methods for the requested resource. --> This does not help me right now, anybody knows how to include an allow header?
Because there are only few threads on this topic at SO, which in my opinion do not answer the questions I had, I'll share my findings how to pass data to the backend via oModels create method:
First Define a type of your result entity (check your oData-Model to know the attributes, e.g. Name and YourID):
var oEntry = {};
oEntry.YourID = "0001";
oEntry.Name = "Peter";
Then fetch your model:
var oModel = sap.ui.getCore().getModel();
Then execute the create operation thanks to: https://sapui5.netweaver.ondemand.com/docs/api/symbols/sap.ui.model.odata.ODataModel.html
jQuery.sap.require("sap.ui.commons.MessageBox");
oModel.create('/EntitySet', oEntry, null, function(){
sap.ui.commons.MessageBox.show(
sap.ui.commons.MessageBox.alert("Success!");
);
},function(){
sap.ui.commons.MessageBox.alert("Error!");
});
Results in Backend in Method "ENTITYSET_CREATE_ENTITY"-Method, where you can retrieve YourID and Name:
DATA: ls_data TYPE ycl_class_mpc=>ts_entity.
CALL METHOD io_data_provider->read_entry_data
IMPORTING
es_data = ls_data.
WRITE ls_data-name.
WRITE ls_data-yourid.
This example applies to single calls, you can see the result in ABAP is a structure. If you need to pass multiple datasets to the backend you should search for batch processing at https://openui5.hana.ondemand.com/docs/api/symbols/sap.ui.model.odata.ODataModel.html
If you are still looking for a good blog on how to make a batch post then have a look at this post http://scn.sap.com/community/developer-center/front-end/blog/2012/11/18/gateway-batch-calls-from-sapui5

MVC Web Api not getting called from javascript ajax

I have a Durandal/Hot Towel test app I'm trying to wire up. I have the below ajax call but I'm getting a 404 error.
GET http/.../api/Pizza/GetPizzasByOrderId?%22a8926610-a713-494c-bb15-46f6487a01c7%22 404 (Not Found)
I can manually change the url to:
http/.../api/GetPizzasByOrderId?orderId=a8926610-a713-494c-bb15-46f6487a01c7
It works. But I would like to know why the other call isn't working or more so, why is the ajax messing the parameter up in the URL and not as data like it does with complex objects. I have a get and a save that is working just fine. The get has zero params and the save is passing a complex object in.
C# Web Api Controller:
public class PizzaController : ApiController
{
[HttpGet]
public IEnumerable<Pizza> GetPizzasByOrderId(Guid orderId)
{
return DATA.GetPizzasByOrderId(orderId);
}
}
JAVASCRIPT:
var dataCall = $.ajax(config.getPizzasByOrderIdUrl, {
data: ko.toJSON(orderId),
type: "get",
contentType: "application/json"
});
Should I just change my JavaScript code to the below and be done with it or is there a better way to talk to the Api?
var getPizzasByOrderId = function (orderId) {
return Q.when($.getJSON(config.getPizzasByOrderIdUrl + "?orderId=" + orderId));
};
You could either use the code as you have it in that last code block, or you could pass in an object in place of your orderId as in the code block below. Either way, the difference is that the orderId parameter is being named.
var dataCall = $.ajax({
url: config.getPizzasByOrderIdUrl,
type: "GET",
data: {orderId : orderId},
});
In regard to why $.ajax() works fine for your POST, you can check this out pretty easily by running these two bits of code and viewing the requests that go across the wire. I recommend using google chrome.
Load a page that has jQuery loaded
Open the developer tools and go to the console
Enter the following code snippet
$.ajax("", {
data: {orderId: 123},
type: "get",
contentType: "application/json"
});
Switch to the network tab and click on the one that ends in ?orderId=123
Notice that it does have the data appended as query string parameters
In the snippet above, replace the "get" with "post"
After you hit enter, you should see another request on the network tab of the developer tools.
Notice that when changing nothing but the request type, the data is moved from the query string to the body. As noted in the comments, WebApi will pull from the body of the request and use the model binder to populate the complex object.

Google Script API + Oauth + Tumblr

Hello,
I'm trying to acess, perform a post, into Tumblr with Oauth api provided by Tumblr) http://tumblr.com/api). I'm using Google Script and I've tryied too many solutions but anyone worked. To implement i've basaed myself into this(https://developers.google.com/apps-script/articles/twitter_tutorial) Google script twitter tutorial, once on Tumblr API web page they say that twitter api is almost the same that tumblr.
Contextualizing,
I've already set the Oauth class methods with data below and substituted consumer and secret keys with values got from the api i've created.
var oauthConfig = UrlFetchApp.addOAuthService("tumblr");
oauthConfig.setAccessTokenUrl(
"http://www.tumblr.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"http://www.tumblr.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"http://www.tumblr.com/oauth/authorize");
oauthConfig.setConsumerKey(<i>consumerkey</i>);
oauthConfig.setConsumerSecret(<i>consumerSecret</i>);
Error,
The code below isnt working as it should be.
var requestData = {
"method": "POST",
"oAuthServiceName": "tumbler",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"https://api.tumblr.com/v2/blog/{blog}.tumblr.com/post?type=text&body=word",
requestData);
The Script to Twitter is almost the same and it works. Im able to perform tweets.
var result = UrlFetchApp.fetch(
"https://api.twitter.com/1/statuses/update.json?status=" + tweet,
requestData);
Response From Server
Request failed for returned code 400. Server response: {"meta":{"status":400,"msg":"Bad Request"},"response":{"errors":["Post cannot be empty."]}}
Possible Solutions
A possible solution can work using this information(got from tumblr.com/api):
OAuth
The API supports the OAuth 1.0a Protocol, accepting parameters via the Authorization header, with the HMAC-SHA1 signature method only. There's probably already an OAuth client library for your platform.
My question is, what am I doing wrong?(my post inst empty, i have 2 params). Had anyone had the same problem? Someone has suggestions?
Thank You.
I don't know anything about the tumblr api, but your http post is empty (the oAuth parameters aren't in the post body, they're advanced options), the body of the post needs to go in the "payload" parameter. See the section "Advanced parameters" in the docs. Or, as you aren't using the post can't you use a get request instead? Remove the method: POST parameter (GET is the default).
Thank You very much Daniel. It worked now!!
Everybody that want use Tumblr + Google Script API + oAuth can use de code below to perform posts.
I created I Google Spreadsheet and then a script there. Before to be able to post I neded to create and app into tumblr.com/api and get secret and consumer keys. Also I've deployed the Google script as an web app(ensure that the version is the last one(the final code)) before to create a new version. After that you go tu publish > deploy as web app !
That twitter tutorial I put on my first question is the only path you need to conclude your job.
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("tumblr");
oauthConfig.setAccessTokenUrl(
"http://www.tumblr.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"http://www.tumblr.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"http://www.tumblr.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "tumblr",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"http://api.tumblr.com/v2/blog/{your_blog}.tumblr.com/posts/queue",
requestData);
}
function doGet(e) {
var tweet = e.parameter.tumblr;
var app = UiApp.createApplication().setTitle("Approved");
var panel = app.createFlowPanel();
authorize();
var encodedTweet = encodeURIComponent(tweet);
var payload =
{
"body" : encodedTweet,
"type" : "text"
};
var requestData = {
"method" : "POST",
"oAuthServiceName": "tumblr",
"oAuthUseToken": "always",
"payload" : payload
};
try {
var result = UrlFetchApp.fetch(
"https://api.tumblr.com/v2/blog/{your_blog}.tumblr.com/post",
requestData);
panel.add(app.createLabel().setText("You have approved: \"" + tweet + "\""));
} catch (e) {
Logger.log(e);
panel.add(app.createLabel().setText(e));
}
app.add(panel);
return app;
}

Resources