C
C#13mo ago
Blaze

Requests

Hello, i have never done something that i will say before, how can i send a request to an API Url, get responce in a form of a .json file and then getting specific values from the .json into variables. How can i do that?
77 Replies
Angius
Angius13mo ago
HttpClient Then .GetFromJsonAsync<T>() Where T is a class that represents the JSON response
PixxelKick
PixxelKick13mo ago
Is the API returning a json file or a json response? Json File you'll need to handle slightly different as it's a text file which has a small bit of headers and you need to open a stream reader, I think? I want to say a text file cant be read exactly the same way as a raw byte stream of text, the file has a little bit of stuff at the start to go "Im a file!"
Blaze
BlazeOP13mo ago
json responce
PixxelKick
PixxelKick13mo ago
oh then thats easy yeh, what Z23Z said is 👍
Blaze
BlazeOP13mo ago
how could i pass data into httpclient
Angius
Angius13mo ago
What data?
Angius
Angius13mo ago
A GET request has no body, only query parameters
Blaze
BlazeOP13mo ago
for exaplme the api im using requires username + password to be passed in order to get a valid login token
Angius
Angius13mo ago
Ah, a POST request then .PostAsJsonAsync<T>(url, data)
PixxelKick
PixxelKick13mo ago
is it FormContent or Body or Url Params?
Blaze
BlazeOP13mo ago
"Content-Type: application/json" body
PixxelKick
PixxelKick13mo ago
Body, aight
Blaze
BlazeOP13mo ago
var client = new HttpClient();

var pairs = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("username", "username"),
new KeyValuePair<string, string>("password", "password")
};
var content = new FormUrlEncodedContent(pairs);

var response = client.PostAsync(URL_LOGIN, content).Result;

if (response.IsSuccessStatusCode) {
string _data = await response.Content.ReadAsStringAsync();
}
var client = new HttpClient();

var pairs = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("username", "username"),
new KeyValuePair<string, string>("password", "password")
};
var content = new FormUrlEncodedContent(pairs);

var response = client.PostAsync(URL_LOGIN, content).Result;

if (response.IsSuccessStatusCode) {
string _data = await response.Content.ReadAsStringAsync();
}
So something like this?
PixxelKick
PixxelKick13mo ago
FormUrlEncodedContent is for when it has to be submitted as FormContent PostAsJsonAsync is when it has to be submitted as just application/json in the body
Blaze
BlazeOP13mo ago
httpclient.PostAsJsonAsync? ah just needed to add a reference to http.formating altho im confused on what type the "value" has to be
Angius
Angius13mo ago
class PostData
{
[JsonProperty("username")]
public string Username { get; init; }
[JsonProperty("password")]
public string Password { get; init; }
}
class PostData
{
[JsonProperty("username")]
public string Username { get; init; }
[JsonProperty("password")]
public string Password { get; init; }
}
var client = new HttpClient();

var data = new PostData {
Username = ...,
Password = ...,
}
var response = await client.PostAsJsonAsync(url, data);
var responseData = response.ReadFromJsonAsync<SomeClass>();
var client = new HttpClient();

var data = new PostData {
Username = ...,
Password = ...,
}
var response = await client.PostAsJsonAsync(url, data);
var responseData = response.ReadFromJsonAsync<SomeClass>();
SomeClass being a class that describes the data you get from the endpoint
Blaze
BlazeOP13mo ago
okay thanks also if you dont mind how can i enable cs9+ , i cant find <LangVersion> inside my .csproj
Angius
Angius13mo ago
What's the framework version you're using?
Blaze
BlazeOP13mo ago
i find that in .csproj?
Angius
Angius13mo ago
Yep
Blaze
BlazeOP13mo ago
4.8
Angius
Angius13mo ago
Oof Why not use a recent version of .NET instead?
Blaze
BlazeOP13mo ago
idk xD i never got to update it +idk how to do it
Angius
Angius13mo ago
You probably created a project with .NET Framework instead of .NET For reference, $newproject
MODiX
MODiX13mo ago
When creating a new project, prefer using .NET over .NET Framework, unless you have a very specific reason to be using .NET Framework. .NET Framework is now legacy code and only get security fix updates, it no longer gets new features and is not recommended. https://cdn.discordapp.com/attachments/569261465463160900/899381236617855016/unknown.png
Blaze
BlazeOP13mo ago
never touched those things
Angius
Angius13mo ago
Did you not create this project, then?
Blaze
BlazeOP13mo ago
aight lemme remake my project i did but i used .net framework
Angius
Angius13mo ago
Well, shouldn't have
Blaze
BlazeOP13mo ago
dw i didnt go much into it aigh so i got 7.0 rn
Angius
Angius13mo ago
8.0 is current Might have to update VS to use it, tho
Blaze
BlazeOP13mo ago
hm gimme a sec i updated it, we will talk tmr if thats fine i have to do smt rn
PixxelKick
PixxelKick13mo ago
I wish "paste json as class" automated this, hopefully eventually this becomes a thing
Blaze
BlazeOP13mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ ive got the framework on my project how do i enable cs 9 now?
Angius
Angius13mo ago
If you have a .NET 8 project, you should be on C# 12 from the get-go
Blaze
BlazeOP13mo ago
ah okay tyty
Blaze
BlazeOP13mo ago
ive never met this error before:
No description
Blaze
BlazeOP13mo ago
i mean i did but i do not understand it
Angius
Angius13mo ago
You need the extension method from... uh, whatever namespace See if quick fixes fix it
Blaze
BlazeOP13mo ago
ah okay
Angius
Angius13mo ago
System.Net.Http.Json is where thos extension methods are
Blaze
BlazeOP13mo ago
now it doesnt show up in COM oh okay there was http.extentions one installed it and included it still doesnt fix it
Angius
Angius13mo ago
Wym "installed"? It's not a nuget, no need to install anything
Blaze
BlazeOP13mo ago
it is its not in the COM list for me
Blaze
BlazeOP13mo ago
installing this fixed it
No description
Angius
Angius13mo ago
Huh, maybe it is, then
Blaze
BlazeOP13mo ago
before i installed the latest vs i didnt have to install it, cus i installed a package requireing it before which prob installed it @ZZZZZZZZZZZZZZZZZZZZZZZZZ sorry for the ping, i stopped working on this for some time as of irl stuff, how do i get the data from the class inputed into ReadFromJsonAsync<>();?
Angius
Angius13mo ago
The example you mentioned is how There isn't anything more to it
Blaze
BlazeOP13mo ago
im confused lmfao what example did i mention
Angius
Angius13mo ago
My message you replied to
Blaze
BlazeOP13mo ago
i got my "responeData" i got that but how do i get the value that has been returned from the response
Angius
Angius13mo ago
From responseData
Blaze
BlazeOP13mo ago
like my class has a int Token, how do i get that Token from responseData
Angius
Angius13mo ago
The SomeClass class should describe the data you expect to receive
Blaze
BlazeOP13mo ago
yeah ive got that
Angius
Angius13mo ago
So if you expect to receive
{
"status": "running",
"count": 67162,
"identifier": "781b-1-3bb2-1"
}
{
"status": "running",
"count": 67162,
"identifier": "781b-1-3bb2-1"
}
you will have a class
class MyCoolData
{
[JsonProperty("status")]
public string Status { get; init; }
[JsonProperty("count")]
public int Count { get; init; }
[JsonProperty("identifier")]
public string Identifier { get; init; }
}
class MyCoolData
{
[JsonProperty("status")]
public string Status { get; init; }
[JsonProperty("count")]
public int Count { get; init; }
[JsonProperty("identifier")]
public string Identifier { get; init; }
}
and after getting the data from the stream
var responseData = await response.ReadFromJsonAsync<MyCoolData>();
var responseData = await response.ReadFromJsonAsync<MyCoolData>();
you can get the status with
var s = responseData.Status;
var s = responseData.Status;
Blaze
BlazeOP13mo ago
yea but how do i get the value of "Count" for example from responseData
Angius
Angius13mo ago
responseData.Count
Blaze
BlazeOP13mo ago
i did that with my "Token" variable but it wasnt under responsedata
Angius
Angius13mo ago
MyCoolData responseData = await response.ReadFromJsonAsync<MyCoolData>();
MyCoolData responseData = await response.ReadFromJsonAsync<MyCoolData>();
this might be easier to understand
Blaze
BlazeOP13mo ago
tyty, im getting status 443 from the api url, it means that the url endpoint doesnt exist?
Angius
Angius13mo ago
I don't remember every status code by heart Look up what it means on MDN
Blaze
BlazeOP13mo ago
No description
Blaze
BlazeOP13mo ago
No description
Angius
Angius13mo ago
Notice your lack of await
Blaze
BlazeOP13mo ago
im blind sorry fr this time late night coding 10/10 would not recommend im confused, out of nowhere it throws an "System.Text.Json.JsonException: ''I' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.'" from System.Text.Json.JsonException, i didnt touch that part of my code, google search did not help
Angius
Angius13mo ago
What's the actual response you get from the API? Run it via some REST client like Bruno or Nightingale Or even just open it in the browser Chances are, that for some reason what you get from that URL isn't valid JSON
Blaze
BlazeOP13mo ago
how can i pass the json parms trought tho
Angius
Angius13mo ago
Right, that's why I mentioned using some client You can pass params there at will Alternatively, read the response as a string and log it to the console
Blaze
BlazeOP13mo ago
ill extract the response into a plain text file
Angius
Angius13mo ago
That'll do in a pinch as well Yeah
Blaze
BlazeOP13mo ago
i get returned "Internal Server Error" as plain string text, an issue of the api was already created on github but closed ill make anothjer one
Angius
Angius13mo ago
Ah, that'll do it, yeah Might want to check the response status first, before trying to deserialize it
Blaze
BlazeOP13mo ago
i think its 505
Angius
Angius13mo ago
That way you can actually tell that an error has occured instead of crashing the app
Blaze
BlazeOP13mo ago
nvm i have trycatch dw Yeah ill try tmr some poeple were saying they get same issue around same time.
Want results from more Discord servers?
Add your server