C
C#16mo ago
Grin

❔ How can I connect to an API?

I recently created a Xamarin app for android that I want to connect to a server (this app will never be available to the public, its for learning purposes about servers & api only). But I have found that the connection times out a lot. I've noticed that a WinForms app I created connects to my server no problem, the connection is fast and the information is loaded in less than a second. Is it possible to make my Xamarin app connect to a WinForms app (I think that would make the Winforms app an api?) that connects to the server, grabs information the user requested, and send it back to the Xamarin app?
17 Replies
anita
anita16mo ago
Can you show the code of the xamarin app that tried to connect to the api? The last part makes no sense to me, why do you want your winforms app act as a server for a mobile app?
Mayor McCheese
Mayor McCheese16mo ago
The winforms app works fine connecting to the server, xamarin app doesn't connect well to the server; two apps pointing to the same service
anita
anita16mo ago
.
Mayor McCheese
Mayor McCheese16mo ago
Where are you hosting the server
Grin
GrinOP16mo ago
Sorry I went away from this for a bit @kocha
Here is the code where I'm hanging from time to time, its at connection.Open();
private string connectionString = DATASOURCE + port + UN + PS + DB + "Connection Timeout=10;";

public List<Cells> getAllCells(string location)
{
// starting with an empty list
List<Cells> cells = new List<Cells>();
try
{
// connect to the mySQL server
MySqlConnection connection = new MySqlConnection(connectionString);

//create an open connection (this logs into the server) and is where I'm getting stuck for 5 seconds and sometimes freezing
connection.Open();
private string connectionString = DATASOURCE + port + UN + PS + DB + "Connection Timeout=10;";

public List<Cells> getAllCells(string location)
{
// starting with an empty list
List<Cells> cells = new List<Cells>();
try
{
// connect to the mySQL server
MySqlConnection connection = new MySqlConnection(connectionString);

//create an open connection (this logs into the server) and is where I'm getting stuck for 5 seconds and sometimes freezing
connection.Open();
I feel like that ConnectionTimeout=10 increases the speed of the connection, I know it doesnt. Just using it as a placebo to make me feel better. I only wanted to use something I was familiar with. I have 0 experience in API, and a tiny bit with SQL. My personal pc. I'm trying to learn about sql, databases, and how I can change values and stuff. It's working and its incredible honestly. But I'm just having issues with lag. disconnects This stuff has really blown my mind otherwise I'm using something called SQLyog Community
Mayor McCheese
Mayor McCheese16mo ago
This isn't terribly surprising in some respects; you're communicating to your local pc from a phone app over the internet; so lots of stuff can go wrong here.
Grin
GrinOP16mo ago
@.mayormccheese I do have the ports forwarded with a static ip address. So I'm able to access my pc from multiple devices. My laptop with a winform app that does essentially the same thing as my android app is way faster at connecting for some reason though. Do you think my android app would perform faster if I used a restful api? I need to learn about that but I'm worried it wont help.
SOMUCHDOG
SOMUCHDOG16mo ago
Trying to give you the best roadmap I can from your info.. An API is a service that connects the application to your internal services/data. Middleware. To connect to an API, you need to serve your API and take requests on a certain port. The application will then make requests to the IP address of the machine hosting your API and specify the port. Aside from communicating over the network, fundamentally, you are calling a function from another device. For example a REST API for public traffic uses port 443 HTTPS to send to a route on your api:
private async void OnSendRequestClicked(object sender, EventArgs e)
{
try
{
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetStringAsync(ApiUrl);
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(response);

if (apiResponse != null)
{
responseLabel.Text = apiResponse.Message;
}
else
{
responseLabel.Text = "API response is null or invalid.";
}
}
}
catch (Exception ex)
{
responseLabel.Text = $"Error: {ex.Message}";
}
}
private async void OnSendRequestClicked(object sender, EventArgs e)
{
try
{
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetStringAsync(ApiUrl);
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(response);

if (apiResponse != null)
{
responseLabel.Text = apiResponse.Message;
}
else
{
responseLabel.Text = "API response is null or invalid.";
}
}
}
catch (Exception ex)
{
responseLabel.Text = $"Error: {ex.Message}";
}
}
Note: Async/await is something very important to making API/DB requests. You will need to look into this for your connection timeout issues :) Some things to note about how it should work: 1. You are sending a request, and you expect a response to be returned. 2. This request should match the parameters of the function on your API. 3. Sometimes servers are down, and processes may fail. Any time you use await, you should use a try/catch to handle your code if it doesn't come back. 4. This example uses JSON as the data that is sent over the network. It can be other things. 5. You should understand the implications of different ports and encryption, if you send a password over HTTP port 80 instead of HTTPS port 443. Anyone on your network can see them in plain text while monitoring the network. --- Now! The API, Your API will interact with the rest of the code on your server (your apps backend)
using Microsoft.AspNetCore.Mvc;

namespace YourApiName.Controllers
{
[RoutePrefix("api/[controller]")]
[ApiController]
public class HelloController : ControllerBase
{
[HttpGet]
[Route("/ligma")]
public IActionResult Get()
{
var apiResponse = new ApiResponse
{
Message = "Hello, Xamarin!"
};

return Ok(apiResponse);
}
}
}
using Microsoft.AspNetCore.Mvc;

namespace YourApiName.Controllers
{
[RoutePrefix("api/[controller]")]
[ApiController]
public class HelloController : ControllerBase
{
[HttpGet]
[Route("/ligma")]
public IActionResult Get()
{
var apiResponse = new ApiResponse
{
Message = "Hello, Xamarin!"
};

return Ok(apiResponse);
}
}
}
On your API code, C# includes an attribute [ApiController] this tells does some magic under the hood for setting up your API. https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-7.0#apicontroller-attribute The [RoutePrefix("api/[controller]") attribute directly refers to the URL for contacting this API. This will be added to your app to point here 🙂 that one line:
// Your xamarin app request
var response = await httpClient.GetStringAsync("https://twitter.com/api/[controller]/ligma");
// Your xamarin app request
var response = await httpClient.GetStringAsync("https://twitter.com/api/[controller]/ligma");
You can additionally add more routes to your api with different HTTP methods using Attributes to limit the scope of them and Routes. That route can then do whatever you need it to do: make a request to another service, read from your db, print "hello world". Just be aware that you are opening your servers to the public when you open a port, you need to learn how to configure firewalls next to prevent bots from accessing your home pc 🙂
Create web APIs with ASP.NET Core
Learn the basics of creating a web API in ASP.NET Core.
Grin
GrinOP16mo ago
Thank you, I'm still processing what you've typed
SOMUCHDOG
SOMUCHDOG16mo ago
No worries! Start small 🙂 Get one request to work first! This is a big leap for a lot of people in programming. It will be the hardest thing you have done yet for sure. but it's what makes it all come together!
Grin
GrinOP16mo ago
I do want to mention I was trying to create a Json file for my android app, but when I selected the add and searched through all of the file types, the file type json didn't exist.
SOMUCHDOG
SOMUCHDOG16mo ago
You won't be sending a file in the request. You will serialize request as JSON. and Deserialize the response. In your first request, you don't have to worry about serializing, because it is a GET request.
Grin
GrinOP16mo ago
serialize and deserialize is a term I don't know yet What truly buggers me about all of this, is that I'm told to not ever connect directly to my server. I THINK the reason for this is because if someone gets ahold of my program they can decompile it and find the username & password for my server. I really wish I could find a book to read about this similar to how I learned c++ & c#. starting from hello world and making my way up
SOMUCHDOG
SOMUCHDOG16mo ago
I wish I knew of one that was high quality... or any at all now that you mention it. 🥲 Try that Microsoft learn link. You can start with the overview section on the left.
Grin
GrinOP16mo ago
I will, thank you for all the info. I'm actually going to take a break for now. But I'll definitely read into it.
Mayor McCheese
Mayor McCheese16mo ago
sorry I got you pulled onto a work issue all day
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server