DEV Community

William Olsen
William Olsen

Posted on

Hosting a REST API using Impart

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;
Enter fullscreen mode Exit fullscreen mode

Now, we can jump to Main() and write the following:

static void Main(string[] args)
{   
    Rest r = new Rest();
    r.OnRequest += OnRequest;
    r.Start();
}
Enter fullscreen mode Exit fullscreen mode

But wait! What is OnRequest()?

That is the method I made for handling requests:

static void OnRequest(APIEventArgs e, RestContext c)
{

}
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Next, we can respond to the request with the RestContext class.

c.Respond(j);
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

Result

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.

Oldest comments (0)