Maui API IMPLEMENT
Hi i am making maui app which can track stocks. I want to use yahoo finance api from rapidapi but i have no idea how to connect and get json. I have already made weather app using api but with this i have no idea how to do it. Thx for every recomendation
9 Replies
HttpClient
is how you call APIsusing System.Net.Http.Headers;
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://yahoo-finance127.p.rapidapi.com/price/meta"),
Headers =
{
{ "X-RapidAPI-Key", "xxx" },
{ "X-RapidAPI-Host", xxx" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
}
i know it generated me this
but where i can get the json format
Instead of
ReadAsStringAsync()
use ReadAsJsonAsync<T>()
Where T
is a class to deserialize the JSON response toi will get smth like this
"latitude": 52.52,
"longitude": 13.419,
"elevation": 44.812,
"generationtime_ms": 2.2119,
"utc_offset_seconds": 0,
"timezone": "Europe/Berlin",
"timezone_abbreviation": "CEST",
"hourly": {
"time": ["2022-07-01T00:00", "2022-07-01T01:00", "2022-07-01T02:00", ...],
"temperature_2m": [13, 12.7, 12.7, 12.5, 12.5, 12.8, 13, 12.9, 13.3, ...]
},
"hourly_units": {
"temperature_2m": "°C"
}
?
I need this, then i will convert it into c#
If that's that the API returns, then yes, that's what you'll get
You can use that to generate the classes to deserialize into
$jsongen
Instantly parse JSON in any language | quicktype
Whether you're using C#, Swift, TypeScript, Go, C++ or other languages, quicktype generates models and helper code for quickly and safely reading JSON in your apps. Customize online with advanced options, or download a command-line tool.
Convert JSON to C# Classes Online - Json2CSharp Toolkit
Convert any JSON object to C# classes online. Json2CSharp is a free toolkit that will help you generate C# classes on the fly.
result of the api is this

my suggestion is not to use hard coded
HttpClient
s.
Instead, inject them into your application with
you can read more here: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-netUse IHttpClientFactory to implement resilient HTTP requests - .NET
Learn how to use IHttpClientFactory, available since .NET Core 2.1, for creating
HttpClient
instances, making it easy for you to use it in your applications.