RestSharp usage for sending and receiving data - json

I have successfully created my app and now want to connect it to a localhost to check the working of my app. I have been suggested to use restsharp for connecting to the server using php and json to receive data from server.
I have looked at codes for both but do not completely understand how the process works. I have looked into all forums but found could snippets with no explanation as how it works. I have even tried restsharp.org and google search results. Please explain me as to how this works.

RestSharp is a library that helps you invoking REST web services.
You use RestSharp on your client to invoke Rest style Web Services (send and receive data)
Here is an example on the usage of your service:
var client = new RestClient(baseUrl);
var request = new RestRequest("/*rest_resource*/", Method.POST);
// see Rest services
// set the request format - HTTP Content-Type text/xml
request.RequestFormat = DataFormat.Xml;
// add data to the request
request.AddBody("<books><book>RestSharp Book</book></books>");
/* send the request and if your service returns text put the as expected return type; otherwise you will get raw byte array*/
IRestResponse response = client.Execute(request);
//HTTP status code 200-success
Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
Assert.IsTrue(!string.IsNullOrEmpty(response.Data)); // the response is not empty

Related

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();
}

400 (Bad Request) when I request a token

I have written the following code to connect and retrieve a token from the Autodesk. but this does not work properly:
var client = new RestClient("https://accounts.autodesk.com");
client.Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);
var request = new RestRequest("OAuth/RequestToken", Method.POST);
var response = await _client.Execute(request);
Executing the request it throws a bad request exception.
Response status code does not indicate success: 400 (Bad Request).
For consumerKey and consumerSecret I respectively used my email and the associated password that I've already registered in accounts.autodesk.com
How can I understand if I'm sending the request in a wrong format or I just send a wrong consumerKey and consumerSecret. And If they are wrong could you please guide me where I can obtain these parameters from Autodesk?
It's not at all your email and password that you need to use but API keys that are generated from your account on our developer portal.
Please sign up or login to the portal: https://developer.autodesk.com/
And follow the step by step tutorial in order to request a token, there are detailed explanations of the workflow there, it can't be easier than that:
https://developer.autodesk.com/en/docs/oauth/v2/tutorials.
I have created a C# sample and a lib but it hasn't been updated yet to use scopes, you can take a look at the discussion in the issues: https://github.com/Developer-Autodesk/view.and.data-dotnet-wpf.tutorial
Finally we are working on generated wrappers for our REST API's so we will be able to produce more stable samples pretty soon. Check out our blog for upcoming news about that: http://adndevblog.typepad.com/cloud_and_mobile

Parse.com cloud httpRequest response.text does not convert to JavaScript object

I have a http request I am trying to make on an afterSave method in my Cloud Code. I have been able to create my request, and when I console.log(response) it outputs a block that contains the information that I am after. I am aware that response.text is a string so I am trying to run JSON.parse(response.text) so I can access my API response.
I can print out what appears to be an object after running JSON.parse, but much of the data within my response is stripped out. I know it is not the fault of the API because I have another function that runs on the client with the same query and it works correctly.
What is the correct way to parse the response.text from a Parse.Cloud.httpRequest to maintain my data.
Try var result = JSON.parse(response['text']).

Write data not flushing for System.Net.HttpWebRequest Stream

I've been trying to construct a simple HTTP request to post all process data in JSON format to a server with PowerShell 2.0, which I need to use out of necessity. Unfortunately, every time I execute my script on a Windows 7 OS, I notice that the the JSON payload is cut off (very frustrating). The actual payload is very large at around 74,100 bytes in the request body. It is also probably useful to note that this request works successfully on a Windows Server 2012 machine, though I suspect that the payload request size for that particular OS is smaller.
Here is the code:
$request = [System.Net.HttpWebRequest]::Create($endpoint);
$request.ContentType = 'application/json';
$request.Method = 'POST';
$request.Headers.Add('Authorization', "Token " + $authToken);
$seconds = 1000;
$request.Timeout=3*$seconds;
$stringContentBytes = [System.Text.Encoding]::UTF8.GetBytes($stringContent);
$request.ContentLength = $stringContentBytes;
$requestStream = $request.GetRequestStream();
$requestStream.Write($requestContentBytes, 0, $requestContentBytes.length);
$requestStream.Close();
$response = $request.GetResponse();
In this example $endpoint represents the target server endpoint, $stringContent represents the JSON-serialized payload that needs to be sent over the wire, and authToken is a string validation token.
I'm currently pointing $endpoint to a service called Request Bin, which very simply details the HTTP request information in a pretty, readable format. So, I know my server can't be causing the payload split.
Also, I've read through various posts about C# and PowerShell and they all mentioned this should be related to not closing the stream. However, as you can see in the code, I'm very clearly executing $requestStream.Close(), which from my research should be able to successfully flush the request stream.
Does anyone know why the output stream would not be processing all the JSON serialized information?
Whoops, I just realized that the Request Bin service that I was using (in fact) was limiting the request body!