C
C#

Requests

Requests

RRBMKBlaze11/17/2023
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?
AAngius11/17/2023
HttpClient Then .GetFromJsonAsync<T>() Where T is a class that represents the JSON response
PPixxelKick11/17/2023
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!"
RRBMKBlaze11/17/2023
json responce
PPixxelKick11/17/2023
oh then thats easy yeh, what Z23Z said is 👍
RRBMKBlaze11/17/2023
how could i pass data into httpclient
AAngius11/17/2023
What data?
AAngius11/17/2023
A GET request has no body, only query parameters
RRBMKBlaze11/17/2023
for exaplme the api im using requires username + password to be passed in order to get a valid login token
AAngius11/17/2023
Ah, a POST request then .PostAsJsonAsync<T>(url, data)
PPixxelKick11/17/2023
is it FormContent or Body or Url Params?
RRBMKBlaze11/17/2023
"Content-Type: application/json" body
PPixxelKick11/17/2023
Body, aight
RRBMKBlaze11/17/2023
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?
PPixxelKick11/17/2023
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
RRBMKBlaze11/17/2023
httpclient.PostAsJsonAsync? ah just needed to add a reference to http.formating altho im confused on what type the "value" has to be
AAngius11/17/2023
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
RRBMKBlaze11/17/2023
okay thanks also if you dont mind how can i enable cs9+ , i cant find <LangVersion> inside my .csproj
AAngius11/17/2023
What's the framework version you're using?
RRBMKBlaze11/17/2023
i find that in .csproj?
AAngius11/17/2023
Yep
RRBMKBlaze11/17/2023
4.8
AAngius11/17/2023
Oof Why not use a recent version of .NET instead?
RRBMKBlaze11/17/2023
idk xD i never got to update it +idk how to do it
AAngius11/17/2023
You probably created a project with .NET Framework instead of .NET For reference, $newproject
MMODiX11/17/2023
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
RRBMKBlaze11/17/2023
never touched those things
AAngius11/17/2023
Did you not create this project, then?
RRBMKBlaze11/17/2023
aight lemme remake my project i did but i used .net framework
AAngius11/17/2023
Well, shouldn't have
RRBMKBlaze11/17/2023
dw i didnt go much into it aigh so i got 7.0 rn
AAngius11/17/2023
8.0 is current Might have to update VS to use it, tho
RRBMKBlaze11/17/2023
hm gimme a sec i updated it, we will talk tmr if thats fine i have to do smt rn
PPixxelKick11/17/2023
I wish "paste json as class" automated this, hopefully eventually this becomes a thing
RRBMKBlaze11/17/2023
@ZZZZZZZZZZZZZZZZZZZZZZZZZ ive got the framework on my project how do i enable cs 9 now?
AAngius11/17/2023
If you have a .NET 8 project, you should be on C# 12 from the get-go
RRBMKBlaze11/17/2023
ah okay tyty
RRBMKBlaze11/17/2023
ive never met this error before:
No description
RRBMKBlaze11/17/2023
i mean i did but i do not understand it
AAngius11/17/2023
You need the extension method from... uh, whatever namespace See if quick fixes fix it
RRBMKBlaze11/17/2023
ah okay
AAngius11/17/2023
System.Net.Http.Json is where thos extension methods are
RRBMKBlaze11/17/2023
now it doesnt show up in COM oh okay there was http.extentions one installed it and included it still doesnt fix it
AAngius11/17/2023
Wym "installed"? It's not a nuget, no need to install anything
RRBMKBlaze11/17/2023
it is its not in the COM list for me
RRBMKBlaze11/17/2023
installing this fixed it
No description
AAngius11/17/2023
Huh, maybe it is, then
RRBMKBlaze11/26/2023
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<>();?
AAngius11/26/2023
The example you mentioned is how There isn't anything more to it
RRBMKBlaze11/26/2023
im confused lmfao what example did i mention
AAngius11/26/2023
My message you replied to
RRBMKBlaze11/26/2023
i got my "responeData" i got that but how do i get the value that has been returned from the response
AAngius11/26/2023
From responseData
RRBMKBlaze11/26/2023
like my class has a int Token, how do i get that Token from responseData
AAngius11/26/2023
The SomeClass class should describe the data you expect to receive
RRBMKBlaze11/26/2023
yeah ive got that
AAngius11/26/2023
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;
RRBMKBlaze11/26/2023
yea but how do i get the value of "Count" for example from responseData
AAngius11/26/2023
responseData.Count
RRBMKBlaze11/26/2023
i did that with my "Token" variable but it wasnt under responsedata
AAngius11/26/2023
MyCoolData responseData = await response.ReadFromJsonAsync<MyCoolData>();
MyCoolData responseData = await response.ReadFromJsonAsync<MyCoolData>();
this might be easier to understand
RRBMKBlaze11/26/2023
tyty, im getting status 443 from the api url, it means that the url endpoint doesnt exist?
AAngius11/26/2023
I don't remember every status code by heart Look up what it means on MDN
RRBMKBlaze11/26/2023
No description
RRBMKBlaze11/26/2023
No description
AAngius11/26/2023
Notice your lack of await
RRBMKBlaze11/26/2023
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
AAngius11/26/2023
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
RRBMKBlaze11/26/2023
how can i pass the json parms trought tho
AAngius11/26/2023
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
RRBMKBlaze11/26/2023
ill extract the response into a plain text file
AAngius11/26/2023
That'll do in a pinch as well Yeah
RRBMKBlaze11/26/2023
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
AAngius11/26/2023
Ah, that'll do it, yeah Might want to check the response status first, before trying to deserialize it
RRBMKBlaze11/26/2023
i think its 505
AAngius11/26/2023
That way you can actually tell that an error has occured instead of crashing the app
RRBMKBlaze11/26/2023
nvm i have trycatch dw Yeah ill try tmr some poeple were saying they get same issue around same time.

Looking for more? Join the community!

C
C#

Requests

Join Server
Want results from more Discord servers?
Add your server
Recommended Posts
Why is my grid on Line 28 not calling back to my other script called Grid?✅ Visual Studio 2022 Failing to Create C# ProjectWhat's happening here?✅ Help with creating shapes on a windows form appI have created a windows form app to display shapes on a bitmap, my circle function works fine but mNo inbuilt functionsHello, im a year 1 student so my knowledge is not that massive. So i have this task for university wSignalR initial connection takes way too long (logs included in comments)Hey there. So I have two versions of the same application, using essentially the same code. One of ✅ How to make DontDestroyOnLoad work for only single scene?Hello! I have a problem. In my game, when I am on my Main Menu Scene and trying to load Main Game ScUI is lagging while scrolling a listViewHi, I wanted to create an application that retrieves data from the API and displays it. I'm having tHow can i fix this error code?he's giving me an error code for private?Visual Studio 2022 ExtensionI'm working on a visual studio 2022 Extension. But as soon as i import it inside the visual studio 2✅ ValidationContext in ASP.NETWhat does ObjectInstance and ObjectType mean? afaik 1) ValidationContext is basically on which claUpdated from 2021 to 2022 version of unity, getting NavMeshSurface related error.Hey y'all, I'm an absolute newbie trying to make a basic game and figured the unity tutorials would Cache not clearing, what am I missing?Does anyone know why this cache is not clearing? I am trying to implement simple rate limiting an aiCal (webcal://) does not doing a sync in outlook365I have my .net core app, and my app generates a link using iCal.NET nuget, and initially it generateDesign Pattern for mapping generic class type to implementationHey all, I'm working on an executor service that maps an executor record of a generic type to an ex✅ Blazor Tutorial (Todo List) Doesn't WorkHello guys, I'm new in Blazor. ```@page "/todo" <PageTitle>Todo</PageTitle> <h1>Todo (@todos.CountString AppendI have the following code: ``` blablabla.1 { row1.withCode row2.withCode row3.withCode row4.Best way to limit file size when downloading a urlSo im adding a way to ahve custom images for xp but dont want to have people put in custom urls thatHi guys I wrote a code but I need to do it simplerSo I wrote a code on c# but I need to do it simpler to make algoritm from it can you help here is coHello World taking 30 seconds + to runHonestly baffled as to how this is possible. I'm running an ubuntu docker container locally on my m1Card GameSo im making a card game, i have 7 dynamic buttons which i want to display 7 shuffled cards, how doe