DEV Community

William Olsen
William Olsen

Posted on

3 2

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay