I am trying to figure out how to use the Refit library to make GET requests but I do not know why it is not working. I am following the example on the refit github page. What am I missing? It seems like the GetUser("octocat") method is not working. I've tried searching for other examples on how to use refit but wasn't able to find anything.
private static async void getUser()
{
var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");
var octocat = await gitHubApi.GetUser("octocat");
}
public class User
{
[JsonProperty("login")]
public string Login { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("avatar_url")]
public string AvatarUrl { get; set; }
[JsonProperty("gravatar_id")]
public string GravatarId { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("html_url")]
public string HtmlUrl { get; set; }
[JsonProperty("followers_url")]
public string FollowersUrl { get; set; }
[JsonProperty("following_url")]
public string FollowingUrl { get; set; }
[JsonProperty("gists_url")]
public string GistsUrl { get; set; }
[JsonProperty("starred_url")]
public string StarredUrl { get; set; }
[JsonProperty("subscriptions_url")]
public string SubscriptionsUrl { get; set; }
[JsonProperty("organizations_url")]
public string OrganizationsUrl { get; set; }
[JsonProperty("repos_url")]
public string ReposUrl { get; set; }
[JsonProperty("events_url")]
public string EventsUrl { get; set; }
[JsonProperty("received_events_url")]
public string ReceivedEventsUrl { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("site_admin")]
public bool SiteAdmin { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("company")]
public string Company { get; set; }
[JsonProperty("blog")]
public string Blog { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("email")]
public object Email { get; set; }
[JsonProperty("hireable")]
public object Hireable { get; set; }
[JsonProperty("bio")]
public object Bio { get; set; }
[JsonProperty("public_repos")]
public long PublicRepos { get; set; }
[JsonProperty("public_gists")]
public long PublicGists { get; set; }
[JsonProperty("followers")]
public long Followers { get; set; }
[JsonProperty("following")]
public long Following { get; set; }
[JsonProperty("created_at")]
public System.DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")]
public System.DateTimeOffset UpdatedAt { get; set; }
}
interface IGitHubApi
{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
If you want to query GitHub API you need to set a User-Agent
There's 2 way to do this with Refit:
1 - Set the headers on your contract
[Headers("User-Agent: My Favorite User Agent!")]
public interface IGitHubApi
{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
2 - Use a HttpClient and set it there
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("User-Agent", "My Favorite User Agent!");
httpClient.BaseAddress = new Uri("https://api.github.com");
var gitHubApi = RestService.For<IGitHubApi>(httpClient);
var user = await gitHubApi.GetUser("octocat");
If you are using the Github API than You need to set the UserAgent in the Header,
just as follows,
{
BaseAddress = new Uri("https://api.github.com"),
DefaultRequestHeaders = {UserAgent = { ProductInfoHeaderValue.Parse("NakWarsi")}} //here I have put my username("NakWarsi") what you need to replace with your username
};
_restApiService = RestService.For<IGitHubApi>(_client);
Here I have created a sample project using Github take a look for detailed information
Related
I using Realm database at my Xamarin project
I have realm object with this model
public class UserModel: RealmObject
{
public string Id { get; set;}
public string Email { get; set; }
public string Password { get; set; }
public byte[] UserAvatar { get; set; }
public string ApiKey { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Birthday { get; set; }
public int Country_id { get; set; }
public bool IsAuthorized { get; set; }
public string Base64Avatar { get; set; }
public string Telephone { get; set; }
}
I need to update Name property.
How I try to do this
var realm = Realm.GetInstance();
var user_check = realm.All<UserModel>().First();
user_check.Name = "Test"
and get this error
How I can fix this?
Adding/Updating/Deleting to Realm object must be done inside a transaction, easiest way is to wrap it in Write method.
realm.Write(() =>
{
user_check.Name = "Test";
});
For more info, check the Rleam Write docs
I am having issues deserializing a nested JSON array from the Genius lyric website API. I formulated the object using http://json2csharp.com. When I deserialize the object, I am unable to access the properties inside of the class, which wasn't entirely unexpected, I am just not sure how to properly design an actual solution to the problem. The JSON object conversions work fine when they are not nested.
What would be the best way to go about handling this?
Here is the conversion code:
string test = await G.SearchGeniusASync(textBox1.Text);
var data = JsonConvert.DeserializeObject<GeniusApiObject>(test);
Here is my class:
class GeniusApiObject
{
public class Meta
{
public int status { get; set; }
}
public class Stats
{
public bool hot { get; set; }
public int unreviewed_annotations { get; set; }
public int concurrents { get; set; }
public int pageviews { get; set; }
}
public class PrimaryArtist
{
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
public class Result
{
public int annotation_count { get; set; }
public string api_path { get; set; }
public string full_title { get; set; }
public string header_image_thumbnail_url { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public int lyrics_owner_id { get; set; }
public string lyrics_state { get; set; }
public string path { get; set; }
public int? pyongs_count { get; set; }
public string song_art_image_thumbnail_url { get; set; }
public Stats stats { get; set; }
public string title { get; set; }
public string title_with_featured { get; set; }
public string url { get; set; }
public PrimaryArtist primary_artist { get; set; }
}
public class Hit
{
public List<object> highlights { get; set; }
public string index { get; set; }
public string type { get; set; }
public Result result { get; set; }
}
public class Response
{
public List<Hit> hits { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Response response { get; set; }
}
}
This is the source for the SearchGeniusASync method in case it is helpful:
public async Task<string>SearchGeniusASync(string searchParameter)
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", clientAccessToken);
var result = await httpClient.GetAsync(new Uri("https://api.genius.com/search?q=" + searchParameter), HttpCompletionOption.ResponseContentRead);
var data = await result.Content.ReadAsStringAsync();
return data;
}
This is the scope I am given access to:
https://i.imgur.com/9mZMvfp.png
Here's a sample JSON request in plaintext:
https://pastebin.com/iA8dQafW
GeniusApiObject is not needed in the code, but I'll leave it in just because it helps organize things (may be that something else also has a RootObject from the auto-generator).
The problem is that you are trying to deserialize to what is just an empty class, the class itself has no properties, so you can't deserialize to it. You need to deserialize to the GeniusApiObject.RootObject.
var data = JsonConvert.DeserializeObject<GeniusApiObject.RootObject>(test);
Will deserialize to the .RootObject subclass. This is verified working:
Where I'm using File.ReadAllText("test.json") to load the example API data provided.
Here is a .NET Fiddle showing it working (without the root object and only one song in the response). Thanks to #maccttura.
I recently tried using the twitch json api, i never had experience with json so it was a nice challenge but then i used json2csharp.com and converted a json string to a class like this:
class TwitchAPI
{
public class Preview
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string template { get; set; }
}
public class Links
{
public string self { get; set; }
public string follows { get; set; }
public string commercial { get; set; }
public string stream_key { get; set; }
public string chat { get; set; }
public string features { get; set; }
public string subscriptions { get; set; }
public string editors { get; set; }
public string teams { get; set; }
public string videos { get; set; }
}
public class Channel
{
public bool mature { get; set; }
public string status { get; set; }
public string broadcaster_language { get; set; }
public string display_name { get; set; }
public string game { get; set; }
public string language { get; set; }
public int _id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public object delay { get; set; }
public string logo { get; set; }
public object banner { get; set; }
public string video_banner { get; set; }
public object background { get; set; }
public string profile_banner { get; set; }
public object profile_banner_background_color { get; set; }
public bool partner { get; set; }
public string url { get; set; }
public int views { get; set; }
public int followers { get; set; }
}
public class Stream
{
public long _id { get; set; }
public string game { get; set; }
public int viewers { get; set; }
public string created_at { get; set; }
public int video_height { get; set; }
public int average_fps { get; set; }
public int delay { get; set; }
public bool is_playlist { get; set; }
}
}
Now i try to access the viewers but it doesn't let me. I do it like this.
TwitchAPI twitchapi = new TwitchAPI();
string viewers = "" + twitchapi.Stream.viewers;
Stream is the name of a class within TwitchAPI - you haven't declared any fields within the TwitchAPI class at all, as far as we can see. So you could use:
TwitchAPI.Stream stream = new TwitchAPI.Stream();
string viewers = stream.viewers.ToString();
... but there's no stream associated with an instance of TwitchAPI at the moment.
(As an aside, I believe there are plenty of Twitter API clients available... if your aim is to do something with Twitter rather than to work on building your own Twitter API, I would suggest using an existing one.)
You need to create an instance if you want to access Stream.
If you want to access like the way you do, then create a property under TwitchApi class like this
public Stream Stream
{
get;
set;
}
Then you can access it as,
TwitchAPI twitchapi = new TwitchAPI();
string viewers = "" + twitchapi.Stream.viewers;
Also, you can avoid having nested classes unless there is something specific you are planning to achieve.
I'm programming a C# implementation for the Qualtrics API (v 2.5) using RestSharp. When calling the method getUserIds, it returns a list of users in JSON format (see the example output below).
The problem/question I face is that for each user object (the list of objects under Result) it generates a different id, starting with URH_. When using json2csharp it assumes ofcourse that it's always a different class, while in fact it's absolutely the same one as you can see in the output, and as is stated in the documentation of the api. How can I best resolve this - so that I can make a class UserData that I can reuse? Because now I obviously always see these random URH_ prefixed classes in each response.
NOTE: I was thinking I could try to massage the response first, and when I get the response replace each URH_ prefixed object under the root Result object with a "UserData" string - but I feel this is breaking the rules a bit, and thought the community would have a better solution?
Below is the raw JSON output (note that I removed sensitive information):
{"Meta":{"Status":"Success","Debug":""},"Result":{"URH_3wpA9pxGbE0c7Xu":{"DivisionID":null,"UserName":"user.name#domain.com","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_4SjjZmbPphZGKDq","UserEmail":"x.x#x.x","UserAccountStatus":"Active"},"URH_57vQr8MVXgpcPUo":{"DivisionID":"DV_XXXXXXXX","UserName":"jxxxx#xx.xxx","UserFirstName":"X","UserLastName":"X","UserAccountType":"UT_BRANDADMIN","UserEmail":"xxxx#xxg.xxx","UserAccountStatus":"Active"},"URH_6ujW1EP0QJOUaoI":{"DivisionID":"DV_XXXXXXXYZ","UserName":"x.xckx#xxx.xyz","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_XXXXXABCD","UserEmail":"c.c#cc.com","UserAccountStatus":"Active"}}}
This is what I get when generating a model using json2csharp:
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class URH3wpA9pxGbE0c7Xu
{
public object DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH57vQr8MVXgpcPUo
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH6ujW1EP0QJOUaoI
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class Result
{
public URH3wpA9pxGbE0c7Xu URH_3wpA9pxGbE0c7Xu { get; set; }
public URH57vQr8MVXgpcPUo URH_57vQr8MVXgpcPUo { get; set; }
public URH6ujW1EP0QJOUaoI URH_6ujW1EP0QJOUaoI { get; set; }
}
public class RootObject
{
public Meta Meta { get; set; }
public Result Result { get; set; }
}
It's simple - just use Dictionary<string, UserData> generic type for Result field:
public class Response
{
public Meta Meta { get; set; }
public Dictionary<string, UserData> Result { get; set; }
}
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class UserData
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
for 3 days i'm trying to send my object to my webapi. I just can't do it from c# :/
I was trying PostAsync method, i was trying to send json (but then I can't deserialize), i was trying to use JObject but can't do nothing with it. I just don't know how to do this.
I got rly simple method
public string PostMethod(Location param)
{
var test = param;
return test.name;
}
how can I send Location object from c# so I won't get null in webapi ? Only thing i've achived is to send a simple type like 'string'. But none of my metrhods works with more complex objects.
Below Location object
public partial class Location
{
public Location()
{
this.Category = new HashSet<Category>();
}
public int id { get; set; }
public Nullable<System.DateTime> create_date { get; set; }
public Nullable<System.DateTime> modify_date { get; set; }
public Nullable<int> create_user_id { get; set; }
public Nullable<int> modify_user_id { get; set; }
public string name { get; set; }
public string description { get; set; }
public Nullable<int> photo_id { get; set; }
public string www { get; set; }
public string count_data { get; set; }
public string status { get; set; }
public Nullable<double> latitude { get; set; }
public Nullable<double> longitude { get; set; }
public string city { get; set; }
public string country { get; set; }
public string zip { get; set; }
public string telephone { get; set; }
public string street { get; set; }
public virtual AzureMedia AzureMedia { get; set; }
public virtual Users Users { get; set; }
public virtual Users Users1 { get; set; }
public virtual ICollection<Category> Category { get; set; }
}
Did you install the newest Web API from NuGet? And you need the Json.NET too for this.
This should do the trick:
Location loc = new Location( ..... );
var jsonFormatter = new JsonMediaTypeFormatter();
HttpContent content = new ObjectContent<Location>(loc , jsonFormatter);
HttpResponseMessage responseMessage = client.PostAsync(uri, content).Result;