Sending JSON data to rest api - api

I have started to learn about REST API. So far I have been able to call my REST API post data using the form and also to get values from my REST API. Now I am trying to learn to send my data to my REST API using JSON object. I have been searching on the net and reading on StackOverflow on how to implement it but so far there is no luck. I am looking for some basic code examples where I can get an idea of how it's done. If some could help me with some codes on how to send data to my REST API using JSON and also how to retrieve that JSON data in my REST API it will be very helpful to me in learning REST API(Just the basic codes I hope it shouldn't take much of your time to post some codes). Btw I am using Jersey to implement my REST API. Thanks in Advance :) It really will be helpful to me in understanding sending JSON data to my web service Thanks again :)
The language is JAVA(JAX-RS implemented in Jersey)

While sending data in json request, your request should be in the form of a map (key value pair ). Key should be your attribute name and values as the value for the attribute.
For example if you are trying to find a employee using employeeid the your request should be of the form {data:{"employeeid":"1"}}
Be more specif about which platform you are using to call the RESTservice.
Hope this will help you.

var clientCreateOrder = new RestClient("#######################");
var requestCreateOrder = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
//Use below code for creating and sending dynamic json objects to RESTAPI
object[] purchase_units_arr = new object[1];
purchase_units_arr[0] = new
{
amount = new
{
currency_code = "USD",
value = "100.00"
}
};
var body = new
{
intent = "CAPTURE",
purchase_units = purchase_units_arr,
};
//Serialize Json object
request.AddParameter("undefined", new JavaScriptSerializer().Serialize(body).ToString(), ParameterType.RequestBody);
IRestResponse responseCreateOrder = client.Execute(request);

Related

How to get string from httpclient request

I tried to get twitch api information but request dosent show anything
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.twitch.tv/helix/streams?game_id=33214"))
{
request.Headers.TryAddWithoutValidation("Client-ID", "ozzdg2w66nugbxdhrzzy5d7z");
var response = await httpClient.SendAsync(request);
}
}
I would use api request to get output precise number, but twitch channel names are not working anymore and you need channel ID which are private.
Basically what I need are 3 things:
Is channel live (true/false)
Live viewership count
thumbnail picture
Is there a way get those data? Or I need to know the secret ID?
I didn't get the conection between your topic and the description of your problem.
But if you want to request stream information you have to use the right endpoint url.
Like: https://api.twitch.tv/helix/streams?user_login=USER_NAME
For more information read the reference documentation https://dev.twitch.tv/docs/api/reference/#get-streams

Acumatica API get all attachments

I have a problem while trying to get attachment from ACUMATICA through API service.
As the example in http://acumaticaopenuniversity.com/pdf/T210_Acumatica_Web_Services.pdf page 36
Example code here
But I don't know how many files here and what are their names? How can I get all attachment of this entity?
Thank in advance.
The contract based web service API has a straightforward GetFiles interface for getting all files of an entity. When you don't have special requirements that forces you to use the screen based web-service API, I'd recommend you use the contract based one.
Interface:
File[] GetFiles(Entity entity)
Usage pseudo-code:
using (DefaultSoapClient soapClient = new DefaultSoapClient())
{
soapClient.Login("username", "password", "CompanyLoginName", null, null);
File[] files = soapClient.GetFiles((Entity)soapClient.Get(new Entity { EntityIntField = new IntSearch { Value = 1 } }));
}
Contract based web service API reference:
http://acumaticaopenuniversity.com/courses/i210-contract-based-web-services/

Add track to playlist SoundCloud API

In my Windows Phone App, I'm using the following code to add a track to playlist (i.e. a PUT request to playlists/id endpoint)
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AccessToken);
HttpResponseMessage response = await httpClient.PutAsync(endpoint, new StringContent(data));
response.EnsureSuccessStatusCode();
}
where "data" is JSON data the form:
{"playlist":{"tracks":["TrackId(to be added)"]}}
The above code returns "OK"(200) response but the track is NOT added to the playlist!
What am I doing wrong? Stuck on it for two days. Thanks in advance!
I use Put to replace track ids in set.
here is sample code
for (String s : trackIds)
nameValuePairs.add(new BasicNameValuePair("playlist[tracks][][id]", s.trim()));
String url = "https://api.soundcloud.com/playlists/" + setId + ".json";
httpPut(url, nameValuePairs);
The problem was that the JSON data (of the request body) was not formatted correctly.
"data" must be of the form:
{"playlist":{"tracks":[{"id":"__"}, {"id":"__"}, {"id":"__"}]}}
Here the id-value pair must be present for
every track already present in the playlist, as well as
the track that you want to add to the playlist
(Remember, this is a PUT request. So, you need to update data i.e. update the "tracks" property of the "playlist")

Crawl Wikipedia using ASP.NET HttpWebRequest

I am new to Web Crawling, and I am using HttpWebRequest to crawl data from sites.
As of now I was successfully able to crawl and get data from my wordpress site. This data was a simple user profile data. (like name, email, AIM id etc...)
Now as an exercise I want to crawl wikipedia, where I will search using the value entered into textbox at my end and then crawl wikipedia with the search value and get the appropriate title(s) from the search.
Now I have the following doubts/difficulties.
Firstly, is this even possible ? I have heard that wiki has robot.txt setup to block this. Though I have heard this only from a friend and hence not sure.
I am using the same procedure I used earlier, but I am not getting the required results.
Thanks !
Update :
After some explanation and help from #svick, I tried the below code, but still not able to get any value (see last line of code, there I am expecting an html markup of the search result page)
string searchUrl = "http://en.wikipedia.org/w/index.php?search=Wikipedia&title=Special%3ASearch";
var postData = new StringBuilder();
postData.Append("search=" + model.Query);
postData.Append("&");
postData.Append("title" + "Special:Search");
byte[] data2 = Crawler.GetEncodedData(postData.ToString());
var webRequest = (HttpWebRequest)WebRequest.Create(searchUrl);
webRequest.Method = "POST";
webRequest.UserAgent = "Crawling HW (http://yassershaikh.com/contact-me/)";
webRequest.AllowAutoRedirect = false;
ServicePointManager.Expect100Continue = false;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(data2, 0, data2.Length);
requestStream.Close();
var responseCsv = (HttpWebResponse)webRequest.GetResponse();
Stream response = responseCsv.GetResponseStream();
// Todo Parsing
var streamReader = new StreamReader(response);
string val = streamReader.ReadToEnd();
// val is empty !! <-- this is my problem !
and here is my GetEncodedData method defination.
public static byte[] GetEncodedData(string postData)
{
var encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
return data;
}
Pls help me on this.
You probably don't need to use HttpWebRequest. Using WebClient (or HttpClient if you're on .Net 4.5) will be much easier for you.
robots.txt doesn't actually block anything. If something doesn't support it (and .Net doesn't support it), it can access anything.
Wikipedia does block requests that don't have their User-Agent header set. And you should use an informative User-Agent string with your contact information.
A better way to access Wikipedia is to use its API, rather than scraping. This way, you will get an answer that's specifically meant to be read by a custom applications, formatted as XML or JSON. There are also dumps containing all information from Wikipedia available for download.
EDIT: The problem with your newly posted code is that your query returns a 302 Moved Temporarily response to the searched article, if it exists. Either remove the line that forbids AllowAutoRedirect, or add &fulltext=Search to your query, which will mean you won't get redirected.

Passing a string param to a RESTful service during POST action

I am having a RESTful service with the following method:
[WebInvoke]
string GetDataFromStringAsString(string xmlString);
My client call to the method is as below:
var client = new RestClient();
client.BaseUrl = serviceBaseUrl;
var request = new RestRequest(method){RequestFormat = DataFormat.Xml};
request.Resource = resourceUrl;
request.AddParameter("text/xml", requestBody,
ParameterType.RequestBody);
var response = client.Execute(request);
Let us take a string to post as "Hello World".
Now the string that i post to the above method gives me a 400 Bad
request. In order to get it working i had to wrap the above string in
a element as shown below:
<string xmlns="http://schemas.microsoft.com/2003/10/
Serialization/">Hello World</string>
Now when i post the above string i get a success response back from
the server.
Why is that i have to manually wrap the string to make it work. Is
there a way that i can achieve to post a string without doing the
above manually.
The only other way that I am aware of is to use stream as your input parameter. e.g.
[WebInvoke]
string GetDataFromStringAsString(stream xmlString);
The problem with .Net 4 WCF REST is that fundamentally WCF only knows how to pass two types of info, either XML or a stream of bytes. Personally, I would use WCF Web API instead of the standard WCF REST library because you are going run into lots more of these kinds of issues.