Api request in Swift - json

I want to use a recipe API for an app. I have registered and obtained a key for an API. However, I don't know where to put my key in the URL so I can paste it into the browser and get the JSON response.
This is the example Curl request
$response = Unirest\Request::get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false&ingredients=apples%2Cflour%2Csugar&limitLicense=false&number=5&ranking=1",
array(
"X-Mashape-Key" => "KEY",
"X-Mashape-Host" => "spoonacular-recipe-food-nutrition-v1.p.mashape.com"
)
);
This is what I get when I search the URL:
{
"message":"Missing Mashape application key. Go to http:\/\/docs.mashape.com\/api-keys to learn how to get your API application key."
}
If anyone knows how to create the full URL with the key or another way to get the Json response in Swift it would be really appreciated.
Thank you

If you want to call an API in Swift, I would recommend using the Alamofire library found here: https://github.com/Alamofire/Alamofire.
In order to authenticate to an API call you have to follow their documentation to find out how they want you to authenticate. Some services have no authentication, while others use a one time use token and some use an API key passed through the request header. It looks like this API call requires the key and host to be passed through the request header. Using Alamofire, the request would look something like this:
let headers: HTTPHeaders = [
"X-Mashape-Key": "KEY",
"X-Mashape-Host": "spoonacular-recipe-food-nutrition-v1.p.mashape.com"
]
Alamofire.request("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false&ingredients=apples%2Cflour%2Csugar&limitLicense=false&number=5&ranking=1", headers: headers).responseJSON { response in
debugPrint(response)
}
If you want to test API calls without coding the request in the app before hand, I would recommend downloading an application called Postman. This will allow you to test APIs and see their responses to help you in your swift app.

Related

Extract user from authentication token

I have created custom Oauth2 service and configured API to use it according to the article: https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-oauth2
Using Developer Portal I see that access token is sent to the API endpoint. However I need to have one more piece of information sent to my endpoint. The access token looks like this:
{"access_token":"e_Pt_0mEUKfMk7DzN7QDmb4tx6syaMM9d7Ei9UH4y1pYipErNHZFz9dU5ZmdTIvr2R4fD1GxJZY-Bsyt7tIpm7uKFScrrKRAKBVGeU3T7R1WTiBV3WglPK1OHZgOSpIY","token_type":"bearer","expires_in":3600,"user":"T81lum-5p6QvDR7l6hv7lfE52bAbA2ylWBnv9CZEzNb0B"}"
I need to extract the user property of the token and send it to API endpoint. Is it possible?
Thank you
Just share an idea about this. the user name is encoded in the bear token that can be parsed with JWT. You can add policy in <inbound> where you parse token and save user name to header then pass to your backend. the official document already provided the JWT parser
Jwt jwt = AsJwt(put_your_token_in_here)
String userName = jwt.Claims.GetValueOrDefault("name")
see JWT token.
You can parse the JSON and extract the user id, but it's going to be dependent on the language you're using.
In Node.JS, it's pretty straightforward (here assuming the auth blob is a string, and not yet parsed):
let userid = JSON.parse( auth_blob ).user;
In Java using GSON:
JsonElement jsonTree = parser.parse( auth_blob );
JsonElement userElement = jsonTree.get("user");
String user = userElement.getAsString();
and so on... searching for "parse JSON" and your language of choice will help you out there.
There's a short tutorial for how to embed a json extract in Azure here:
https://learn.microsoft.com/bs-latn-ba/azure/api-management/policies/cache-response?toc=api-management/toc.json
<!-- Extract a JSON object containing lat/long from the response and serialize it into a variable. -->
<set-variable name="latlong" value="#(((IResponse)context.Variables["response="""]).Body.As<JObject>
()["results"][0]["geometry"]["location"].ToString())"/>
So, I suppose that you could do the same thing for your auth blob:
<set-variable name="user" value="#((auth_blob).Body.As<JObject>
()["user"].ToString())"/>
Please edit if this is incorrect - I'm just guessing here.
You cannot retrieve user details from auth code. You can do it using an access token.
Please refer to similar question and answer here

Create URL with JSON object as header

I'm exploring Bitso API (Bitso is a mexican crypto exchange).
The docs of the API is well explained at some languages such as Python and Ruby for its use. The problem here is that there are no examples using straight URLs for request.
What I'm planning to do is to create the URL that the code is creating on its requests function.
There is a request for balance account, that is the data I'd like to get.
According documentation, this is a private request that need some headers at the request (Key, nonce and signature), you can take a look here.
The code to make this request in Python is the following one:
import time
import hmac
import hashlib
import requests
bitso_key = "BITSO_KEY"
bitso_secret = "BITSO_SECRET"
nonce = str(int(round(time.time() * 1000)))
http_method = "GET"
request_path = "/v3/balance/"
json_payload = ""
# Create signature
message = nonce+http_method+request_path+json_payload
signature = hmac.new(bitso_secret.encode('utf-8'),
message.encode('utf-8'),
hashlib.sha256).hexdigest()
# Build the auth header
auth_header = 'Bitso %s:%s:%s' % (bitso_key, nonce, signature)
# Send request
response = requests.get("https://api.bitso.com/v3/balance/", headers={"Authorization": auth_header})
print(response.content)
So based in this I could say that the URL is something like this:
https://api.bitso.com/v3/balance/Bitso%20<Key>:<nonce>:<signature>
I'm sure that I'm wrong with that supposition, I understand that headers={"Authorization": auth_header} seems to be a JSON object used as header in the URL, but I'd like to know how that JSON object is translated at the URL to make a request. I'd like to copy-paste that URL at the browser and get the data as response.
I need that URL so I could use it to connect the service to a Business Intelligence tool.
Thanks!
According to the documentation this Authorization is a header in the request. You can try using postman but you still need hash the destination URL with your api key and the nonce to avoid replay attacks.

Twitter OAUTH Acces Token Response in JSON

I'm using Twitter's REST API to authorize an app. I just authorized the app with
https://api.twitter.com/oauth/authorize
and got an oauth_verifier from the redirect uri.
Then I just used
https://api.twitter.com/oauth/access_token
to get an access_token.
The problem is that the format of response I got from this method is text/plain. It's just like
oauth_token=783897656863051776-5hQfcJTv4FzFpPcyVRbnjPUbJXR29&oauth_token_secret=MViTPOOCaHNZrW6HTIFZ340bq1rutJKL8oqkBxRp2aiW&user_id=783897656863051776&screen_name=sWest&x_auth_expires=0
My query is that how to get the response in application/json format.
Any help will be appreciated !!!
You will need to parse it like application/x-www-form-urlencoded content, any language with HTTP Client libraries should provide this functionality. But it isn't clear what language and libraries you are using.
This example uses joauth library to parse
protected static Map<String, String> parseTokenMap(String tokenDetails) {
KeyValueHandler.SingleKeyValueHandler handler =
new KeyValueHandler.SingleKeyValueHandler();
KeyValueParser.StandardKeyValueParser bodyParser =
new KeyValueParser.StandardKeyValueParser("&", "=");
bodyParser.parse(tokenDetails, Collections.singletonList(handler));
return handler.toMap();
}

Receive Json post into a controller from 3rd party application

I have to wrote a method that will receive a json post from a 3rd party site.
and then I will have to convert the json to a model and do some operation.
I am trying this:
[System.Web.Http.AcceptVerbs("POST")]
public MyCustomModel GetStatus(string jsonObj)
{
///something goes here..
}
when I call this from fiddler, it never works. Fiddler says
No HTTP resource was found that matches the request URI
what am I doing wrong?? Any ideas would be much appreciated..

How can I access auth-only Twitter API methods from a web application

I have a web application for iPhone, which will ultimately run within a PhoneGap application - but for now I'm running it in Safari.
The application needs to access tweets from Twitter friends, including private tweets. So I've implemented OAuth using the Scribe library. I successfully bounce users to Twitter, have them authenticate, then bounce back.
At this point the web app has oAuth credentials (key and token) which it persists locally. From here on I'd like it to user the Twitter statuses/user_timeline.json method to grab tweets for a particular user. I have the application using JSONP requests to do this with unprotected tweets successfully; when it accesses the timeline of a private Twitter feed, an HTTP basic authentication dialog appears in the app.
I believe that I need to provide the OAuth credentials to Twitter, so that my web application can identify and authenticate itself. Twitter recommends doing so through the addition of an HTTP Authorization header, but as I'm using JSONP for the request I don't think this is an option for me. Am I right in assuming this?
My options therefore appear to either be putting the oAuth credentials as query-string parameters (which Twitter recommends against, but documentation suggests still supports); or proxying all the Tweets through an intermediate server. I'd rather avoid the latter.
I access the Twitter API using URLs of the form
http://api.twitter.com/1/statuses/user_timeline.json?user_id=29191439&oauth_nonce=XXXXXXXXXXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1272323042&oauth_consumer_key=XXXXXXXXXX&oauth_signature=XXXXXXXXXX&oauth_version=1.0
When user_id is a public user, this works fine. When user_id is a private user, I get that HTTP Basic Auth dialog. Any idea what I'm doing wrong? I'm hoping it's something embarrassingly simple like "forgetting an important parameter"...
The oAuth stanza needs to be exact, as per http://dev.twitter.com/pages/auth#auth-request - I ended up building an Authorization: header that I could first check with curl.
I built it using the really helpful interactive request checker at http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/
Here's a friends API request for a protected user:
curl -v -H 'Authorization: OAuth realm="https://api.twitter.com/1/friends/ids.json", oauth_consumer_key="XXXXXXXXXXXXXXXX", oauth_token="XXXXXXXXXXXXXXXX", oauth_nonce="XXXXXXXXXXXXXXXX", oauth_timestamp="1300728665", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_signature="XXXXXXXXXXXXXXXX%3D"' https://api.twitter.com/1/friends/ids.json?user_id=254723679
It's worth re-iterating that as you've tried to do, instead of setting the Authorization header via e.g. jquery's beforeSend function, that for cross-domain JSONP requests (which can't add HTTP headers) you can make oAuth requests by putting all the relevant key/value pairs in the GET request. This should hopefully help out various other questioners, e.g
Set Headers with jQuery.ajax and JSONP?
Modify HTTP Headers for a JSONP request
Using only JQuery to update Twitter (OAuth)
Your request looks like it has a couple of problems; it's missing the user's oauth_token plus the oauth_signature doesn't look like it has been base64 encoded (because it's missing a hex encoded = or ==, %3 or %3D%3D respectively).
Here's my GET equivalent using oAuth encoded querystring params, which you can use in a cross-domain JSONP call:
https://api.twitter.com/1/friends/ids.json?user_id=254723679&realm=https://api.twitter.com/1/friends/ids.json&oauth_consumer_key=XXXXXXXXXXXXXXXX&oauth_token=XXXXXXXXXXXXXXXX&oauth_nonce=XXXXXXXXXXXXXXXX&oauth_timestamp=1300728665&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=XXXXXXXXXXXXXXXX%3D
I was struggling with similar problem of making JSONP requests from Jquery, the above answer helped just to add what I did to achieve my solution.
I am doing server to server oauth and then I send oauth token, secret, consumer key and secret (this is temporary solution by the time we put a proxy to protect consumer secret). You can replace this to token acquiring code at client.
Oauth.js and Sha1.js download link!
Once signature is generated.
Now there are 2 problems:
JSONP header cannot be edited
Signed arguments which needs to be sent as part of oauth have problem with callback=? (a regular way of using JSONP).
As above answer says 1 cannot be done.
Also, callback=? won't work as the parameter list has to be signed and while sending the request to remote server Jquery replace callback=? to some name like callback=Jquery1232453234. So a named handler has to be used.
function my_twitter_resp_handler(data){
console.log(JSON.stringify(data));
}
and getJSON did not work with named function handler, so I used
var accessor = {
consumerSecret: XXXXXXXXXXXXXXXXXXXXXX,
tokenSecret : XXXXXXXXXXXXXXXXXXXXXX
};
var message = { action: "https://api.twitter.com/1/statuses/home_timeline.json",
method: "GET",
parameters: []
};
message.parameters.push(['realm', "https://api.twitter.com/1/statuses/home_timeline.json"]);
message.parameters.push(['oauth_version', '1.0']);
message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
message.parameters.push(['oauth_consumer_key', XXXXXXXXXXXXXXXX]);
message.parameters.push(['oauth_token', XXXXXXXXXXXXXXX]);
message.parameters.push(['callback', 'my_twitter_resp_handler']);
OAuth.completeRequest(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
Create url with base url and key value pairs from parameterMap
jQuery.ajax({
url: url,
dataType: "jsonp",
type: "GET",
});