How to use an API - api

I'm studying Informatics but somehow I don't get that one.
I want to set up the PayPal NVP-API.
(NVP = Name value Pair).
Can someone tell me how I can CALL an API-Command?
I don't even know which programming language I have to take :S
Reference to the Tutorial: PayPal NVPAPI Developer Guide

It sounds like you might be a bit over your head on this one, but don't worry it's not that difficult.
When they say POST they literally mean an HTTP POST, but since its SSL you'd need to provide credentials also.
jQuery AJAX http://api.jquery.com/jQuery.ajax/ would be a good place to start..
$.ajax({
url : 'paypalurl',
type : 'POST', //IMPORTANT
username : 'username',
password : 'password',
data : 'YOUR DATA HERE' //form or something of the like
success : function(r) {
//handle the success here
},
error : function(e) {
//uh-oh
}
});
This should get you started, but please be careful this is financial data.

Related

Facebook js api - "unsupported get request" error

I'm trying to get some (I think allowed) information in my app. I have an access token that has the following info:
App ID: <my app id> : iHOUSEListingPoster - Test 001
Type: User
App-Scoped User ID: <user id> : Joe Webb
Valid: True
Scopes: email, pages_show_list, pages_read_engagement, pages_manage_posts, public_profile
I'm trying this:
FB.api( "/me",
"GET",
{fields: 'name'},
function(get_fb_info_response) {
console.log("Here: ", get_fb_info_response
});
And getting this error:
"Unsupported get request. Object with ID 'me' does not exist, cannot be loaded due to missing permissions, or does not support this operation"
I have tried with both "/me" and "/me/". And while I want name, picture and email, I tried limiting it to just name, and still. What am I missing here?
Try this:
FB.api('/me?fields=name', function(response) {
console.log('me', response);
});
I'm not sure if api function from FB does have this signature you're using.
Edit
After searching at Facebook docs, found that the signature you were using is valid as well. Then, I went to do some tests here. And I was able to reproduce the same error you have mentioned when calling the function like this:
FB.api("/<123>/", "GET", { fields: 'name' }, function(response) {
console.log('response', response);
});
To fix it, you need to remove < and >, for example:
FB.api("/123/", "GET", { fields: 'name' }, function(response) {
console.log('response', response);
});
Calling /me and /me/ endpoint returned no error in my test.
In this screenshot you can see the tests I have run directly at my browser's console.
Ok, I finally figured out what the problem is/was here (sheepish face). We have a couple of Facebook accounts here at the company. One is the container for my app and it's test app, the other is a more general company account. I was logged into the general company account. When I tried my app, it grabbed some random app from that account, which wasn't the app that matched the access token (which I think is possible wrong on Facebook's part), therefore this error was thrown.
Once I logged into the correct Facebook account, all works as expected.

Trying to log in to gmail while using TestCafe

I am learning TestCafe and am trying to create an account on a website and then logging in to Gmail to find the activation link. When I try to do this I just get a browser isn't secure message when I get to the part to enter a password. How do I get Gmail to trust TestCafe?
While you might succeed in doing so, this is not a good approach because:
it's slow doing this via GUI
it's britle because selectors will likely change, and you have no control over Google email selectors, so you won't even know if they change them
A better approach wuld be to use a service like Mailosaur where you can create an account and receive emails that you can later query via an API. Instead of doing a whole e2e flow over GUI, you request an email on Mailosaur's API, and if such an email exists, you'll receive a response you can parse and check for various things.
I've done this in the past, you can see my post here: https://sqa.stackexchange.com/questions/40427/automating-verification-of-sent-email-sms-messages/45721#45721 It's exactly Mailosaur and Testcafe (plus it requires axios as a package), so it seems to be what you're looking for.
To add the same code here:
import config from '../config';
import { customAlphabet } from 'nanoid';
import axios from 'axios';
import Newsletter from '../Objects/newsletter';
async function request (reqObject) {
try {
return await axios(reqObject);
} catch (error) {
console.error(error);
}
}
function serverId () {
return process.env.MAILOSAUR_SERVER_ID;
}
function mailosaurFullEmail (id) {
return (id ? id : nanoid()) + '.' + serverId()
+ '#' + config.mailosaurDomain;
}
fixture `Newsletter`
.page(baseUrl);
test
('Sign Up For Newsletter', async t => {
const id = (customAlphabet('1234567890', 10))();
await t
.typeText(Newsletter.newsEmailInput, mailosaurFullEmail(id))
.click(Newsletter.consent)
.click(Newsletter.sendButton);
let res = await request({
method: 'POST',
url: config.mailosaurUrlEmail + serverId(),
headers: {
'Authorization': 'Basic '
+ Buffer.from(process.env.MAILOSAUR_API_KEY)
.toString('base64'),
'Content-Type': 'application/json'
},
data: {
sentTo: mailosaurFullEmail(id)
}
});
await t
.expect(res.status).eql(200);
});
and it requires some config values:
{
"mailosaurUrlEmail": "https://mailosaur.com/api/messages/await?server=",
"mailosaurDomain": "mailosaur.io"
}
This is definitely much better, but it still has some limitations:
Mailosaur's API can still change, so it won't be exactly without any maintenance
it assumes that an email is sent immediately after a user action (newsletter in my case), but that might be far from reality in many situations such as when emails are sent to a queue where it can easily take several minutes to send an email
If you absolutely have to do it via Gmail, you will still be better off looking at their API that should allow you to search and query email messages as well.
There is an issue related to the Google login. You can try turning on the "Allow less secure apps" Google account setting to workaround this issue. Please note that this setting is available for the disabled 2-Step Verification.

New to api testing pre-request scripts - Automatically getting access token with OAuth 2.0 Grant Type 'Client Credentials'

I have been stuck for days on this and looked through many articles, but can not find a script that can help me.
The basis of the script is to automatically get authorization token, before i use a POST method.
As said before when getting a access token for this particular api the grant type is Client Crentials and the following fields are needed when manually getting the token :-
Token Name, Grant Type, Access Token URL, Client ID, Client Secrect, Scope and Client Authentication.
Is there a simple script that i can do this for me before actually doing the POST as it tiresome manually getting the token.
Thanks in advance with any help.
Kind Regards
Just an update i have found a way of actually getting the token now , so if you do the following.
Add a new request
Select 'Post'
Enter the api url
Click 'Body'
Click 'x-www-form-urlencoded'
I entered the following 'Keys'(enter your own corresponding 'values') - 'client_id', 'client_secret', 'scope' and 'grant type'
Click 'Send'
This will get you your token, i now need to find a way to either extract the token in a new request or find a way of putting this in the pre-request scripts, so I am able to enter the data need as 'raw' JSON.
Again if anyone can help, would appreciate it.
Kind Regards
Would this be any help to you? Or at least get you closer to what you need?
If you add this script to the Collection level pre-request script it will get the token and set this as the jwt variable. You can use this variable in the Headers for the main requests, using the {{jwt}} syntax - This script also gets the expiry_in value from the token response and sets this as a variable.
On each request in the collection, it will run the script and check to see if you have the AccessTokenExpiry and jwt properties in the environment file, it also checks to see if the token has expired. If any of those statements are true, it will get another token for you. If those are ok, it will use what you have set.
const moment = require('moment')
const getJWT = {
url: `<your token base path>/Auth/connect/token`,
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: 'grant_type', value: 'client_credentials'},
{key: 'scope', value: '<scope details>'}
{key: 'client_id', value: 'your creds'}
{key: 'client_secret', value: 'your creds'}
]
}
}
var getToken = true
if (!_.has(pm.environment.toObject(), 'AccessTokenExpiry')
|| !_.has(pm.environment.toObject(), 'jwt')
|| pm.environment.get('AccessTokenExpiry') <= moment().valueOf()) {
} else {
getToken = false
}
if (getToken) {
pm.sendRequest(getJWT, (err, res) => {
if (err === null) {
pm.environment.set('jwt', `Bearer ${res.json().access_token}`)
var expiryDate = moment().add(res.json().expires_in, 's').valueOf()
pm.environment.set('AccessTokenExpiry', expiryDate)
}
})
}
To access the Collection level elements, if you hover over the collection name and click the ... icon, this will display a list of menu options. Select edit.

submitting a form to the server as json

I am trying to submit a form to the server with the params in JSON.
form.submit({
url:'JSONSaveEntry',
method:'POST'
});
but it sends everything as form-www-urlencoded.
I already checked that no field has isFile set to true (but then, it would send as multipart-formdata) and that standardSubmit is false.
I also tried to use
Ext.Ajax.request({
url:'JSONSaveEntry',
method:'POST',
params:form.getValues()
});
and
Ext.Ajax.request({
url:'JSONSaveEntry',
method:'POST',
params:Ext.encode(form.getValues())
});
Every submission is done as form-www-urlencoded, although the docs clearly state "Performs a Ajax-based submission of form values (if standardSubmit is false)". But then, this sentence is already proven wrong because whenever a file field is in the form, the form is submitted as multipart.
So, does anyone know how I can get the form submitted as JSON?
Possibility 2: I know that it works if I submit a model via model.save(), but how would I create a model from a form on-the-fly (without hardcoding the fields twice)?
I think below would solve your purpose.
Ext.Ajax.request({
url:'JSONSaveEntry',
method:'POST',
headers: { 'Content-Type': 'application/json' },
jsonData : JSON.stringify(form.getValues()),
success : function(response){ console.log("response from server")},
failure : function(error){console.log(error)}
});

Sencha Touch - RESTful load() specific instance URL problem (Store/model)

It seems there is a problem with loading a specific instance (load() function) using the rest proxy in a model/store object. example:
Code:
Ext.regModel('User', {
fields: ['id', 'name', 'email'],
proxy: {
type: 'rest',
url : '/users'
}
});
//get a reference to the User model class
var User = Ext.ModelMgr.getModel('User');
//Uses the configured RestProxy to make a GET request to /users/123
User.load(123, {
success: function(user) {
console.log(user.getId()); //logs 123
}
});
This code is copied from Sencha touch's API. the generated URL is http://localhost/users?_dc=... instead of the desired (and documented) url http://localhost/users/123.
it also happens when using the store.load with a parameter.
Am I doing something wrong here?
Thanks
T
It seams the id parameter has been documented but not implemented. This has been discussed in the sencha forum [link]. A few non complete fixes are written in post #8 and post #13.