After finishing up my REST API class in Impart, I thought I should share how to easily host a REST API using it. Disclaimer: All code in this post is subject to change as I update and rework the library.
First, we need to add Impart to our project. Find out how in the README here: https://github.com/PixelatedLagg/Impart
Next, we will add our using
statements:
using Impart;
using Impart.API;
Now, we can jump to Main()
and write the following:
static void Main(string[] args)
{
Rest r = new Rest();
r.OnRequest += OnRequest;
r.Start();
}
But wait! What is OnRequest()
?
That is the method I made for handling requests:
static void OnRequest(APIEventArgs e, RestContext c)
{
}
The Rest
class in Impart is using JSON formatting for responses, so let's use the convenient Json
struct to handle response creation. Now, I hear your sighs behind the monitor, but this stays easy - trust me.
In this line, I create a simple JSON document titled 'Impart':
Json j = new Json("Impart", ("Developer", "William Olsen"), ("Current Downloads", 519), ("Current Stars", 8));
Next, we can respond to the request with the RestContext
class.
c.Respond(j);
Putting it all together:
using Impart;
using Impart.API;
public class Program
{
static void Main(string[] args)
{
Rest r = new Rest();
r.OnRequest += OnRequest;
r.Start();
}
static void OnRequest(APIEventArgs e, RestContext c)
{
Json j = new Json("Impart", ("Developer", "William Olsen"), ("Current Downloads", 519), ("Current Stars", 8));
c.Respond(j);
}
}
The default port for hosting is 8080, however you can specify a custom one in the constructor of Rest
.
Visiting localhost:8080
, we are greeted with this:
In short, it worked!
As I continue to rework Impart, I will be adding an easy way to host SOAP APIs and make JSON/XML formatting simpler.
Stay posted to see all new updates to the internet's simplest website/networking library, Impart.
Top comments (0)