i want to get complete list of followers using REST API with c# but i only get 20 followers
var postBody = "screen_name=" + Uri.EscapeDataString(screen_name);//
resource_url += "?" + postBody;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
var response = (HttpWebResponse)request.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
JObject j = JObject.Parse(result);
JArray data = (JArray)j["users"];
So with the above codes, i get only 20 followers and from here i see in an answer there is a broken link to a package. Also, i am using only Newton.Json. How do i get complete list of followers?
you have to add parameters to your query with the cursor provided in the json returned in your first query.
https://dev.twitter.com/rest/reference/get/followers/ids
I am not sure I do understand what your problem is. But getting all the followers of a member is not a 'simple' process.
I would suggest that you try out the project Tweetinvi and learn more about this feature here : https://github.com/linvi/tweetinvi/wiki/Get-All-Followers-Code.
You will first want to get all the users ids and then get the user objects via.
Then you can use var userIds = User.GetUsersFromIds(userIds); to get the users from Followers.
NOTE : Remember that Twitter has rate limits on its API. Take a look at https://github.com/linvi/tweetinvi/wiki/Rate-Limits to learn how to use them.
For simplicity I would suggest that you use :
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
Related
I am pulling my hair out trying to query the CoinSpot API.
The endpoint for the Read Only API is: https://www.coinspot.com.au/api/ro
The documentation states:
All requests to the API will need to include the following security
data.
Headers: key - Your API key generated from the settings page sign -
The POST data is to be signed using your secret key according to
HMAC-SHA512 method. Post Params: nonce - Any integer value which must
always be greater than the previous requests nonce value.
I try to query the 'List My Balances' endpoint via: https://www.coinspot.com.au/api/ro/my/balances
However, the code I have formulated below always returns an error: "invalid/missing nonce".
I have tried so many different variations and approaches but it is always the same error.
require(httr)
key <- "68z...39k"
secret <- "71A...48i"
result <- POST("https://www.coinspot.com.au/api/ro/my/balances",
body = list('nonce'=as.integer(as.POSIXct(Sys.time()))), add_headers("key"=key,"sign"=openssl::sha512("https://www.coinspot.com.au/api/ro/my/balances",key = secret)))
content(result)
Any help much appreciated.
Ive struggled with this too- the coinspot API guide isn't very clear.
I figured out you are meant to encode the postdata in correct json format using sha512 and add that to the sign header. See example below querying account balances on v2 of the api.
require(httr)
api_key = "68z...39k"
api_secret = "71A...48i"
base_url = "https://www.coinspot.com.au/api/v2/ro"
request = "/my/balances"
nonce = as.character(as.integer(Sys.time()))
postdata = paste0('{"nonce":"',nonce,'"}') # important to get the quotes correct
api_sign = digest::hmac(api_secret, postdata, algo="sha512",raw=F)
result = POST(paste0(base_url, request),
body = list("nonce"=nonce),
add_headers(c("key"=api_key,
"sign"=api_sign)),
encode="json"
)
cat(rawToChar(result$content))
You would change what is in postdata based on what you are doing with the API- this is a simple example to build on. If you want to see what postdata should look like prior to encryption in sign, use cat(rawToChar(result$request$options$postfields)) after making a request.
For me, I was missing the JSON string encoded postdata in the body, including the nonce. As soon as I added that, it started working.
Heres my code in c# using Restsharp and Newtonsoft
//put the nonce at the beginning
JObject joBody = JObject.Parse(#"{'nonce': '" + DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() + "'}");
joBody.Merge(originalBody);
var client = new RestClient(_coinspotSettings.BaseURL);
RestRequest request = new RestRequest(endpoint, Method.POST);
request.AddJsonBody(JsonConvert.SerializeObject(joBody));
request.AddHeader("key", coinspotAccount.APIKey);
request.AddHeader("sign", SignData(coinspotAccount, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(joBody))).ToLower());
request.AddHeader("Content-Type", "application/json");
private string SignData(CoinspotAccount coinspotAccount, byte[] JSONData)
{
var HMAC = new HMACSHA512(Encoding.UTF8.GetBytes(coinspotAccount.APISecret));
byte[] EncodedBytes = HMAC.ComputeHash(JSONData);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i <= EncodedBytes.Length - 1; i++)
stringBuilder.Append(EncodedBytes[i].ToString("X2"));
return stringBuilder.ToString();
}
I am trying to create a new document in documentDB via the rest API. I would use the SDK, but im running the project from asp.net core and the SDK isn't compatible yet.
I would like to have documentDB auto generate the id for the document, but I am having problems with my request.
What should I set the ids value to when creating the document via the documentDB rest api (using id based routing)?
Right now I am getting hit with the 400 bad request error.
Ive tried posting it with the following variations on the id:
No id property
id: null
id: ""
The code i am using is basically what was in the github .net rest examples, i have the replace call, get calls working fine.
Here is my code making the request:
//Create a document
verb = "POST";
resourceType = "docs";
resourceLink = string.Format("dbs/{0}/colls/{1}/docs", databaseId, collectionId);
resourceId =string.Format("dbs/{0}/colls/{1}", databaseId, collectionId);
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
string content = JsonConvert.SerializeObject(document);
StringContent contentMessage = new StringContent(content, System.Text.Encoding.UTF8, "application/json");
contentMessage.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
contentMessage.Headers.ContentType.CharSet = null;
var r = client.PostAsync(baseUri + resourceLink, contentMessage).Result;
System.Diagnostics.Debug.WriteLine(r.Content.ReadAsStringAsync().Result);
return r.Content.ReadAsStringAsync().Result;
You should supply a string value for the "id" property. The auto-id functionality (like Larry mentions) is a client-side feature, not part of the REST API. So when consuming directly from REST, you must generate a Guid (or any unique string) and set the "id" property with that value.
I'm new to Twitter API & trying to get tweets with a specific hashtag in my C# Web application.
I was able to authenticate my app & get JSON from Twitter ,here are some questions/issues I have:
API can only return maximum 100 tweets in one call,so how I can check if I've more tweets?
If somebody have code example to convert that(Twitter's) JSON into custom class object,so
I can count tweets (I tried but getting errors)?
I used this to generate c# classes from json & getting error while doing following:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
RootObject routes_list = (RootObject)json_serializer.DeserializeObject(s);
Tweetinvi manages that for you. Here is an example returning 200 results.
var searchParameter = Search.GenerateSearchTweetParameter("#my_tag");
searchParameter.Lang = Language.English;
searchParameter.SearchType = SearchResultType.Popular;
searchParameter.MaximumNumberOfResults = 200;
searchParameter.Since = new DateTime(2013, 12, 1);
// ... There are many different parameters that can be set
var tweets = Search.SearchTweets(searchParameter);
tweets.ForEach(t => Console.WriteLine(t.Text));
// Get number of objects
var nbTweets = tweets.Count();
Hope this helps.
Certainly Tweetinvi as user64 said, is a great API, please for version 2.1 the following does the job. Be aware of set RateLimitTrack mode
// Set up my credentials in (https://apps.twitter.com)
Auth.SetUserCredentials(consumer_key, consumer_secret, access_token, access_token_secret);
// Enable Automatic RateLimit handling
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
var searchParameter = Search.CreateTweetSearchParameter("#My_Tag");
searchParameter.Lang = LanguageFilter.Spanish; // or English
searchParameter.SearchType = SearchResultType.Recent;
searchParameter.MaximumNumberOfResults = 200; // or any number
searchParameter.Since = new DateTime(2013, 12, 1);
var tweets = Search.SearchTweets(searchParameter); // tweets.Count() has the actual searched tweets
foreach(var item in tweets)
{
// do anything with item and its properties example: item.Text;
}
I want to make an API call where the response is in XML format.
This is the API description: http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm
I have registered and I have a key to use in the request URL.
Could anyone give me an idea of how to make the call and analyse the response?
Thankyou.
Something along the lines of:
var request = WebRequest.Create("http://www.dictionaryapi.com/api/v1/references/collegiate/xml/hypocrite?key=1234");
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
Then you can grab what you need like:
xdoc.Element("ElementName");
I have given
[WebGet(UriTemplate = "/{year}/{issue}/{article}")]
Article GetArticle(string year, string issue, string article);
[OperationContract]
[WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]
Article AddArticle(string year, string issue, Article article);
My URL is http://localhost:1355/Issues.svc/
if I give this I am fetching all data from the database
http://localhost:1355/Issues.svc/2010/June/A
GetArticle method fires for the filtered data to bring from db.
Similarly I have to call the Add Article(WebInvoke) method to insert data in to the database.
How should I call this method in the browser
how my url should be should I give method=post
check this post help you to achieve the task you want :Create REST service with WCF and Consume using jQuery
You won't be able to send an HTTP post from a browser by just modifying the URL. You'll have to have a web page with a HTML form, some Javascript code, some server-side code, or something else that has the ability to make an HTTP POST request to your service URL.
If you are just wanting to test your service while in development, here's a good HTTP debugging tool that you might want to check out: http://fiddler2.com
You can't use post it using browser url.
Try this code
//Creating the Web Request.
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost/DemoApp/Default.aspx") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Source : http://www.dotnetthoughts.net/2009/11/10/post-data-using-httpwebrequest-in-c-sharp/