HTTP GET - nonunknown/Godot-SheetDB GitHub Wiki
- Note that all requests are async, this means that we need a separate thread to get the response
Create your button or other node and attach a csharp script:
public override void _Ready()
{
string result = "";
System.Threading.Thread t = new System.Threading.Thread(async ()=> {
result = await SheetDB.GetUserByID("godete");
GD.Print("done: "+result);
});
t.Start();
}
- result: is where the json response will be
- Thread: Why you are using System.Threading.Thread instead of just Thread? Because Thread is reserved from Godot namespace , i know its a pain in the ass...
- the method we are calling does not exists, because we are going to make it;
Open the SheetDB.cs file and lets create our first get method:
public static async Task<String> GetUserByID(string ID)
{
string body = "";
await ConfigClient();
HttpResponseMessage response = await client.GetAsync(string.Concat(apiUrl,"/ID/",ID));
if (response.IsSuccessStatusCode) {
body = await response.Content.ReadAsStringAsync();
}
return body;
}
- take a look at you api_url var if it does not have a slash in the end
- see sheet-best docs for filtering data -> https://sheet.best/dashboard/docs/filtering-data
- this is my sheet at the moment:
We are going to get the godete row
- run your game and lets see if everything goes well
voila!!!
- Don't worry if your code did not worked, the problem is that our code is working but is far from perfect! We need to handle errors.
public static async Task<String> GetUserByID(string ID) {
string body = "";
await ConfigClient();
try
{
HttpResponseMessage response = await client.GetAsync(string.Concat(apiUrl,"/ID/",ID));
if (response.IsSuccessStatusCode) {
body = await response.Content.ReadAsStringAsync();
}
else {
throw new HttpRequestException(response.ReasonPhrase.ToString());
}
}
catch (HttpRequestException e)
{
GD.Print("Error at sending request to GetUserByID");
GD.Print(e.Message);
}
return body;
}
HttpRequestException
Now if some error occurs , the engine will tell us what happened
- Note: You can see the response.* and what info ou can get from there How do you now the exception type HttpRequestException? Easy dude, look at response var, its a HttpResponseMessage, usually the exception handler has a connection with the operation you are doing.