SOMUCHDOG
❔ How can I connect to an API?
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:
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)
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:
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 🙂
28 replies