I am pretty new to C# and want to create a REST Get request with Basic auth. I'm using RestSharp but i can't find a proper working full example. This is my code:
using RestSharp;
using RestSharp.Authenticators;
namespace HttpClientAPP
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://data.myhost.de");
client.Authenticator = new HttpBasicAuthenticator("user", "xxxx");
var request = new RestRequest("resource",Method.Get);
client.ExecuteGetAsync(request).Wait();
Console.WriteLine("as");
}
}
}
This is thejson answer I expect and i want to parse it to use the data to store it in a MYSQL DB:
{"info": [
{
"method": "GET",
"url": "https://data.myhost.de/zfa-values/{zfaId}",
"description": "Get a ZFA value by id"
},
{
"method": "GET",
"url": "https://data.myhost.de/zfa-values",
"description": "Get a list of available ZFA values"
},
{
"method": "GET",
"url": "https://data.myhost.de/new-zfa-values",
"description": "Get a list of available ZFA values which have not been viewed yet"
},
{
"method": "GET",
"url": "https://data.myhost.de/",
"description": "Get a list of api endpoints"
}
]}
How do I parse the json response?
CodePudding user response:
First, you can use newtosoft json nuget package: Docs: https://www.newtonsoft.com/json
Example:
class ApiEndpoint{
public string Method {get;set;} // or you can use enum
public string Url {get;set;}
public string Description {get;set;}
}
// some logic
public void Fetch()
{
var client = new RestClient("https://data.myhost.de");
client.Authenticator = new HttpBasicAuthenticator("user", "xxxx");
var request = new RestRequest("resource",Method.Get);
var response = client.Get(request);
// read response as json
var json = JsonConvert.DeserializeObject<ICollection<ApiEndpoint>>(response);
// now json will have structure in your example
}
- Other way is to add swagger gen for you server, get openapi.json and then generate sharp client using nswag https://blog.logrocket.com/generate-typescript-csharp-clients-nswag-api/
CodePudding user response:
Look at https://restsharp.dev/v107/#recommended-usage
Get:
public class GitHubClient {
readonly RestClient _client;
public GitHubClient() {
_client = new RestClient("https://api.github.com/")
.AddDefaultHeader(KnownHeaders.Accept, "application/vnd.github.v3 json");
}
public Task<GitHubRepo[]> GetRepos()
=> _client.GetAsync<GitHubRepo[]>("users/aspnet/repos");
}
Post:
var request = new MyRequest { Data = "foo" };
var response = await _client.PostAsync<MyRequest, MyResponse>(request, cancellationToken);
You have classes that represent the json you send/get back, and RestSharp will de/serialize them for you. If you want some help making classes from JSON, take a look at services like http://app.QuickType.io - you paste your json and you get representative classes. The online generators are usually a bit more sophisticated in terms of what they interpret/the attributes they decorate with. Pasting your json into QT gives (you can choose a better name than SomeRoot):
namespace SomeNamespace
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class SomeRoot
{
[JsonProperty("info")]
public Info[] Info { get; set; }
}
public partial class Info
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
}
public partial class SomeRoot
{
public static SomeRoot FromJson(string json) => JsonConvert.DeserializeObject<SomeRoot>(json, SomeNamespace.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this SomeRoot self) => JsonConvert.SerializeObject(self, SomeNamespace.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
And use like:
var res = _client.GetAsync<SomeRoot>("");