Ruby pass header with API - json

So I've been trying to set up my chat bot for Twitch. I want the user to be able to type !stats and then they'll see my Fortnite stats.
They can use the command and stuff, that's not what I'm having a problem with. I'm having some trouble sending a header to Fortnite Tracker API.
They want to recieve this: TRN-Api-Key: somelong-api-key-right-here in the header.
I've tried these methods:
require("httparty")
url = "https://api.fortnitetracker.com/v1/profile/pc/bentearzz"
header = {
key: "TRN-Api-Key: Somelong-api-key-here"
}
response = HTTParty.get(url, header: header)
puts(response.body)
and this
require("net/http")
require("json")
url = "https://api.fortnitetracker.com/v1/profile/pc/bentearzz"
uri = URI(url)
response = Net::HTTP::Get.new(uri)
response.basic_auth("TRN-Api-Key: 7af072f0-d195-4c44-b1b4-a8838080e4c4")
JSON.parse(response)
print(response)
Please help.

Your first one is on the right track. I think there are just a few syntax errors.
url = "https://api.fortnitetracker.com/v1/profile/pc/bentearzz"
headers = {
"TRN-Api-Key": "Somelong-api-key-here"
}
response = HTTParty.get(url, headers: headers)
puts(response.body)

Related

M Language - How to get JSON in HTTP Request Body? (Vimeo API Unsupported Grant Type Error)

I am attempting to create my first PowerBI Custom Connecter to connect to the Vimeo API. I am stuck on the final step of the authorization flow - getting back an access token. When trying out the Connecter in PowerBI, it seems to authenticate properly when I hit the access token endpoint, but I get back a warning "[unsupported_grant_type] Unsupported grant type"
It appears I am not sending the grant_type properly in the request. Here are Vimeo's requirements of what is sent along in the header and body of the request:
Header
Set value to
Authorization
basic base64_encode(x:y), where x is the client identifier and y is the client secret
Content-Type
application/json
Accept
application/vnd.vimeo.*+json;version=3.4
"In the request body, send the grant_type field with the value authorization_code. You must also set code to the authorization code string that you just received and redirect_uri to the redirect URI that you specified previously — don't use a different redirect URI."
{
"grant_type": "authorization_code",
"code": "{code}",
"redirect_uri": "{redirect_uri}"
}
Here is a snippet of code from the Customer Connector I am building. It is within this TokenMethod function that I am trying to fulfill the requirements of the table above. I am getting the sense I am not correctly placing the JSON in the body of the request, but I am stuck on what to try next:
TokenMethod = (grantType, tokenField, code) =>
let
queryString = [
grant_type = "authorization_code",
redirect_uri = redirect_uri,
client_id = client_id,
client_secret = client_secret
],
queryWithCode = Record.AddField(queryString, tokenField, code),
authKey = "Basic " & Binary.ToText(Text.ToBinary("client_id:client_secret"),BinaryEncoding.Base64),
tokenResponse = Web.Contents(token_uri, [
Content = Text.ToBinary(Uri.BuildQueryString(queryWithCode)),
Headers = [
#"Authorization" = authKey,
#"Content-type" = "application/json",
#"Accept" = "application/vnd.vimeo.*+json;version=3.4"
],
ManualStatusHandling = {400}
]),
body = Json.Document(tokenResponse),
result = if (Record.HasFields(body, {"error", "error_description"})) then
error Error.Record(body[error], body[error_description], body)
else
body
in
result;
I'm wondering if someone could please point out where I might be going astray in the code and why I am receiving the [unsupported_grant_type] error.
Many thanks for your time!
I changed Content-Type to "application/x-www-form-urlencoded" and it worked!

Google scripts, using urlFetchApp() for PUT request, I cannot get a response code when server sends 204 no content response

For GET and POST requests for a private server I work with I use in Google Sheets, do something like this, and I get a proper response. I use that response to update data and just as importantly for error checking by evaluating response.getResponeCode().
function postDataToServer(params){
let myjdService = getService();
let orgId = getOrgIdForSelectedOrg();
let link = https://GoodURLForPrivateDataIWorkWithALot/neededurlParameter/anotherNeededURLParameter;
let options = {
'method': 'put',
'payload': JSON.stringify(params),
'headers': {
'Accept': 'application/vnd.PRIVATE.v3+json',
'Content-Type': 'application/vnd.PRIVATE.v3+json',
'authorization': 'Bearer ' + myPrivateService.getAccessToken()
}
};
let response = UrlFetchApp.fetch(link, options);
return response.getResponseCode();
For all the GET and POST requests I do, I get a response. And from that response I can parse a response code. But for the specific server I work with, when I edit a record using PUT, a successful edit returns this:
204 No Content
And further, the last line return response.getResponseCode() returns an error the response is undefined.
Here's the error I get for doing anything with response:
ReferenceError: response is not defined
The PUT is working. I only know this because 1) when I check if edits are made with the server, they are 2) testing the PUT in Postman at least shows me the words "204 No Content" and 3) the documentation says that's exactly what I should expect.
But I still would like to find out how to evaluate this no-content response in my Google Sheets App for proper error tracking. At least some way to get the string "204". Any ideas? I can't even get Google Sheets to do say 204.

How to make a video stream http GET request to img html tag with axios?

I have a Django 2.1 backend that have a video stream endpoint and a Vue-Cli3 as my frontend.
The videostream endpoint in my backend is a GET request. To have the streaming working in my client side all i needed was to add:
<img :src="$store.state.domain + 'cameras/video/' + camera.properties.name + '/'" width="240" alt="Camera live Stream">
This works fine but now i have to protect my back-end route for authenticated users only. For this i just need to add an authentication token in the request header.
The problem is, according to Set custom header for the request made from <img/> tag , an img tag doesn't accept header parameters.
So now I'm trying to build a request using axios library and then stream the request result to my HTML img tag.
my Vue method code so far:
loadStream(){
const vm = this
let accessToken = vm.$store.getters.getAccessToken
let streamURL = `${vm.$store.state.domain}/cameras/video/${vm.camera.properties.name}/`
axios.get(streamURL, {headers: {"Authorization": `Bearer ${accessToken}`},
responseType: 'stream',
adapter: httpAdapter}
).then( response =>{
console.log(`success:${response.data}`)
let imgTag = document.createElement('img')
imgTag.src = URL.createObjectURL(response)
imgTag.classList.add('video-modal', 'popup-video')
imgTag.alt = `Camera ${camera.properties.name} liveStream`
imgTag.setAttribute("crossorigin", '')
let streamDiv = document.getElementById('livestream-img')
streamDiv.appendChild(imgTag)
}).catch( error => {
console.log(`error:${response.data}`)
let imgTag = document.createElement('img')
imgTag.alt = `Camera ${camera.properties.name} liveStream`
let streamDiv = document.getElementById('livestream-img')
streamDiv.appendChild(imgTag)
})
}
All i get is this warning:
Warning: The provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType.
Also my request never ends. Promise will never hit .then() or .catch() because it's streaming. Seems like responseType isn't working properly. am i missing something?
This is my django backend endpoint:
class CameraVideoStreamingView(APIView):
def get(self, request, name):
cam = Camera.objects.get(name=name)
return StreamingHttpResponse(cam.serve_web_stream(),
content_type="multipart/x-mixed-replace;boundary=frame")
I would recommend sending some sort of auth token in the video's query params, and to handle this, implementing a custom Token Authentication Class which gets the token from a query param rather than the headers. You'd then have to update the authentication_classes property of your view with your new authentication class.

Posting to Spotify API for tokens is returning status 415. Am I missing something?

Here is my method for hitting their API for their Authorization Code Flow:
class func obtainAuthTokenPackage(authCode: String) throws
{
//Create a request
var request = URLRequest(url: Gimme.theSpotify.urlFor(endpoint: .requestingTokens)) //"https://accounts.spotify.com/api/token"
request.httpMethod = "POST"
//Build the header
let spotifyClientCreds = Gimme.theSpotify.clientID + ":" + Gimme.theSpotify.clientSecret
let encodedCreds = spotifyClientCreds.data(using: .utf8)!.base64EncodedString()
request.setValue("Basic \(encodedCreds)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//Build the body
var dict = [String:String]()
dict["grant_type"] = "authorization_code"
dict["code"] = authCode
dict["redirect_uri"] = Gimme.theSpotify.redirectURI
var package = Data()
do
{
package = try JSONSerialization.data(withJSONObject: dict)
}
catch
{print("oopsie")}
request.httpBody = package
//Set up a web transaction
let transaction = URLSession.shared.dataTask(with: request) {
(possData, possResp, possErr) in
if let data = possData
{
print(String(data: data, encoding: .utf8)!)
}
}
//Do it
transaction.resume()
}
The print statement near the bottom produces {"error":"server_error","error_description":"Unexpected status: 415"}
Things I've Tried Already:
Changing request.setValue(... to request.addValue(... and vice versa doesn't seem to make a difference.
Using application/x-www-form-urlencoded, changing the http body to "grant_type=authorization_code&code=" + authCode + ...".data(using: .utf8).
When I did this, API responds with a message that I need to set the grant type to authorization_code (which tells me their server isn't parsing my http body correctly).
Moving client credentials from the header to the body (using JSON).
Creating my http body using Swift 4's new JSON encoding tools
Requesting using the Rested app (it's like Postman or HTTPRequestor)
Implementing their Implicit Grant Flow with success. But that doesn't give a refresh token and I need it :(.
Sobbing internally so I don't distract people around me
Changing Content-Type to content-type
Removing the header field that specifies content type
Escaping characters in the redirect-uri (e.g. replacing colons with %3A, slashes with %2F)
Questions I Have:
Status 415 means unsupported media type, so is the Spotify API expecting application/x-www-form-urlencoded instead of JSON?
If you can get Spotify's Authorization Code Flow working in your Swift project, what did you do different?
If you use application/x-www-form-urlencoded, how did you create your http body?
I appreciate any help, thanx guys.
I DID IT! HAHAHAHAHAHAHAHAHAHA!!!!!!!!!!!
//The endpoint expects form-urlencoded
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
//Build a string that has client_id, client_secret, grant_type, the code, and the redirect uri
//It has to be in that order (I didn't try any other order, but I've been having this problem for so long, I don't want to risk anything)
//It has to be in the form "key=value&key=value..." (Standard form url encoded format)
var formEncoded = "client_id=\(Gimme.theSpotify.clientID)"
formEncoded.append("&client_secret=\(Gimme.theSpotify.clientSecret)")
formEncoded.append("&grant_type=authorization_code")
formEncoded.append("&code=\(authCode)")
formEncoded.append("&redirect_uri=\(Gimme.theSpotify.redirectURI)")
//Finally convert it into UTF8 data
let bodyData = formEncoded.data(using: .utf8) //Check that this isn't nil, then proceed
//Stick this stuff in the transaction, and it'll be SUCCESSFULLLLL
Questions I had that I am able to answer now:
- This api endpoint https://accounts.spotify.com/api/token application/x-www-form-urlencoded as the Content-Type.
- What I did different: I included client ID and client secret before the grant_type key in the body instead of putting it in the header
- I created my http body manually as demonstrated by the code segment above.
In conclusion:
- Nothing really fancy needed
- Spotify API documentation is lacking (but c'mon, who's isn't?)
- I'm relieved

POST request not able to find url

I am new to nodejs as well as developing.
I am trying to get a set of data bat from a nutrition site in JSON format. If I formulate the url with my app and api keys along with criteria to paste into the browser I get a JSON data ok. When I try to send a POST request as the site asks for when the request comes back it says it cannot find the url. What it is doing is attaching ':443' to the end of the host url and like I said coming back as an error:
Error: getaddrinfo ENOTFOUND https://api.nutritionix.com/v1_1/search https://api.nutritionix.com/v1_1/search:443
What I would like to do is after the end of the url is append the 'postData'.
Here is my code:
var https = require('https');
var querystring = require('querystring');
var postData = { // Nutrionix required JSON formt
"appId":"MY_APP_KEY",
"appKey":"MY_API_KEY",
"query": "Lentils",
"fields": ["item_name", "nf_calories", "nf_serving_size_qty", "nf_serving_size_unit"],
"sort":{
"field":"score",
"order":"desc"
},
"filters":{
"item_type":"2"
}
};
console.log("This is header dta" + postData);
postBody = querystring.stringify(postData);
var post_options = {
host:"https://api.nutritionix.com/v1_1/search",
"port":"443",
method:"post",
"path":"/",
headers:{"Content-Type":"application/json",
'Content-Length': postBody.length
}
}
console.log(post_options);
var request = https.request(post_options,function(response){
return response;
});
I also am passing this data into the dev HTTP add-on in Chrome and getting back the proper response.
Any help would be appreciated.
Can you please take a look at this documentation?
It seems that you don't need to mention HTTPS
Take the port off, 443 is the default for HTTPS.