REST Service

How to create a simple REST service.

Key takeaways

RestService Component available in the RPC module, services library. This component is used to create REST services that receive remote calls via the HTTP/REST protocol.

Introduction

This tutorial will help you understand how REST services can be created with Pip.Services. It begins by explaining the necessary pre-requisites. Then, it proceeds to explain how to create a simple REST service using the RestService component, and how to configure and run it. It ends by showing the results on a browser.

Creating our REST service

Pre-requisites

In order to create our REST service, we need to import the RestService class, which is available in the services library, RPC module. This can be done with the following command:

import { RestService } from "pip-services3-rpc-nodex";

Request and response objects are objects of the restify library.

using PipServices3.Rpc.Services;

Request and response objects are objects of the Microsoft.AspNetCore.Http library.

import (
	rpc "github.com/pip-services3-gox/pip-services3-rpc-gox/services"
)

Request and response objects are objects of the net/http library.

import 'package:pip_services3_rpc/pip_services3_rpc.dart';

Additionally, we will need to import shelf and shelf_router, which will be used to access our requests.

import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';

from pip_services3_rpc.services import RestService

Additionally, we will need to import Bottle, which will be used to access our requests.

from bottle import request

Not available

REST Service

First, we need to create our REST service. For this, we will create a class that inherits the Pip. Services' component RestService, which has different methods that can be used to handle REST services. The most important one is configure, and we will use it to set up our microservice.

In this class, we first define a method to be used as a handler. In it, we define some parameters that will help us to connect to our application . In our example, this method is called my_page and the parameters are name and message.

We also define the register() method to register the service route. We use the GET method, and as we are not using a schema, we define it as None.

The first part of our code will look something like this:

import { RestService } from "pip-services3-rpc-nodex";


class MyRestService extends RestService {

    constructor(){
        super();
        this._baseRoute = "/my_service";
    }

    private async myPage(req, res){
        let result = req.params.message + req.query.name;
        this.sendResult(req, res, result);
    }

    public register() {
        this.registerRoute("GET", "/my_page/:name", null, this.myPage)
    }

}
public class MyRestService : RestService
{
    public MyRestService() : base()
    {
        _baseRoute = "/my_service";
    }

    private async Task MyPage(HttpRequest req, HttpResponse res, RouteData routeData)
    {

        var parameters = GetParameters(req);

        var name = parameters.GetAsNullableString("name");
        var message = parameters.GetAsNullableString("message");
        var result = message + ", " + name;

        await SendResultAsync(res, result);
    }

    public override void Register()
    {
        RegisterRoute("GET", "/my_page/{name}", this.MyPage);
    }
}

import (
	"context"
	"net/http"
	"os"

	"github.com/gorilla/mux"

	config "github.com/pip-services3-gox/pip-services3-commons-gox/config"
	rpc "github.com/pip-services3-gox/pip-services3-rpc-gox/services"
)

type MyRestService struct {
	*rpc.RestService
}

func NewMyRestService() *MyRestService {
	c := &MyRestService{}
	c.RestService = rpc.InheritRestService(c)
	c.BaseRoute = "/my_service"
	return c
}

func (c *MyRestService) myPage(res http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)

	name := req.URL.Query().Get("message")
	message := vars["name"]
	result := message + ", " + name

	c.SendResult(res, req, result, nil)
}

func (c *MyRestService) Register() {
	c.RegisterRoute("GET", "/my_page/{name}", nil, c.myPage)
}
import 'dart:async';

import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';

import 'package:pip_services3_rpc/pip_services3_rpc.dart';

class MyRestService extends RestService {
  MyRestService() : super() {
    baseRoute = '/my_service';
  }

  FutureOr<Response> myPage(Request req) async {
    var name = req.url.queryParameters['message'];
    var message = req.params['name'];
    var result = message.toString() + ', ' + name.toString();

    return sendResult(req, result);
  }

  @override
  void register() {
    registerRoute('GET', '/my_page/<name>', null, myPage);
  }
}
class MyRestService(RestService):

    def __init__(self):
        super(MyRestService, self).__init__()
        self._base_route = "/my_service"

    def my_page(self, name):
        result = f"{request.query.get('message')}, {name}"
        return self.send_result(result)

    def register(self):
        self.register_route(method="GET", route="/my_page/<name>", schema=None, handler=self.my_page)
        
Not available

Configuration

Now that we have our REST service defined, we will configure and run it. To configure our component, we first need to create an instance of our class and use the method configure to set up our connection protocol, host and port. As the configure method requires a ConfigParams input type, we import this class and use its method “from_tuples” to define our configuration. Lastly, we open our component. The second part of our code will look something like this:

import { ConfigParams } from "pip-services3-commons-nodex";

let myRestService = new MyRestService();

myRestService.configure(ConfigParams.fromTuples(
    "connection.protocol", "http",
    "connection.host", "localhost",
    "connection.port", 15239
));
await myRestService.open("123");

using PipServices3.Commons.Config;

var myRestService = new MyRestService();

myRestService.Configure(ConfigParams.FromTuples(
    "connection.protocol", "http",
    "connection.host", "localhost",
    "connection.port", 15239
));

myRestService.OpenAsync("123").Wait();


myRestService := NewMyRestService()

myRestService.Configure(context.Background(), config.NewConfigParamsFromTuples(
	"connection.protocol", "http",
	"connection.host", "localhost",
	"connection.port", 15239,
))

_ = myRestService.Open(context.Background(), "123")

var myRestService = MyRestService();

myRestService.configure(ConfigParams.fromTuples([
  'connection.protocol',
  'http',
  'connection.host',
  'localhost',
  'connection.port',
  15239
]));

await myRestService.open('123');

from pip_services3_commons.config import ConfigParams

my_rest_service = MyRestService()

my_rest_service.configure(ConfigParams.from_tuples("connection.protocol", "http",
                                                   "connection.host", "localhost",
                                                   "connection.port", 15239))

my_rest_service.open("123")

Not available

Our microservice

Our final code will be:

import { ConfigParams } from "pip-services3-commons-nodex";
import { RestService } from "pip-services3-rpc-nodex";


class MyRestService extends RestService {

    constructor() {
        super();
        this._baseRoute = "/my_service";
    }

    private async myPage(req, res) {
        let result = req.query.message + ', ' + req.params.name;
        this.sendResult(req, res, result);
    }

    public register() {
        this.registerRoute("GET", "/my_page/:name", null, this.myPage);
    }

}

export async function main() {
    let myRestService = new MyRestService();

    myRestService.configure(ConfigParams.fromTuples("connection.protocol", "http",
        "connection.host", "localhost",
        "connection.port", 15239));

    await myRestService.open("123");
}

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;

using PipServices3.Commons.Config;
using PipServices3.Rpc.Services;

namespace ExampleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var myRestService = new MyRestService();

            myRestService.Configure(ConfigParams.FromTuples(
                "connection.protocol", "http",
                "connection.host", "localhost",
                "connection.port", 15239
            ));

            myRestService.OpenAsync("123").Wait();

            Console.Read(); // wait for close
        }
    }

    public class MyRestService : RestService
    {
        public MyRestService() : base()
        {
            _baseRoute = "/my_service";
        }

        private async Task MyPage(HttpRequest req, HttpResponse res, RouteData routeData)
        {

            var parameters = GetParameters(req);

            var name = parameters.GetAsNullableString("name");
            var message = parameters.GetAsNullableString("message");
            var result = message + ", " + name;

            await SendResultAsync(res, result);
        }

        public override void Register()
        {
            RegisterRoute("GET", "/my_page/{name}", this.MyPage);
        }
    }
}

package main

import (
	"context"
	"net/http"
	"os"

	"github.com/gorilla/mux"

	config "github.com/pip-services3-gox/pip-services3-commons-gox/config"
	rpc "github.com/pip-services3-gox/pip-services3-rpc-gox/services"
)

type MyRestService struct {
	*rpc.RestService
}

func NewMyRestService() *MyRestService {
	c := &MyRestService{}
	c.RestService = rpc.InheritRestService(c)
	c.BaseRoute = "/my_service"
	return c
}

func (c *MyRestService) myPage(res http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)

	name := req.URL.Query().Get("message")
	message := vars["name"]
	result := message + ", " + name

	c.SendResult(res, req, result, nil)
}

func (c *MyRestService) Register() {
	c.RegisterRoute("GET", "/my_page/{name}", nil, c.myPage)
}

func main() {
	myRestService := NewMyRestService()

	myRestService.Configure(context.Background(), config.NewConfigParamsFromTuples(
		"connection.protocol", "http",
		"connection.host", "localhost",
		"connection.port", 15239,
	))

	_ = myRestService.Open(context.Background(), "123")

	os.Stdin.Read(make([]byte, 1)) // wait for close
}

import 'dart:async';

import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';

import 'package:pip_services3_commons/pip_services3_commons.dart';
import 'package:pip_services3_rpc/pip_services3_rpc.dart';

class MyRestService extends RestService {
  MyRestService() : super() {
    baseRoute = '/my_service';
  }

  FutureOr<Response> myPage(Request req) async {
    var name = req.url.queryParameters['message'];
    var message = req.params['name'];
    var result = message.toString() + ', ' + name.toString();

    return sendResult(req, result);
  }

  @override
  void register() {
    registerRoute('GET', '/my_page/<name>', null, myPage);
  }
}

void main(List<String> arguments) async {
  var myRestService = MyRestService();

  myRestService.configure(ConfigParams.fromTuples([
    'connection.protocol',
    'http',
    'connection.host',
    'localhost',
    'connection.port',
    15239
  ]));
  await myRestService.open('123');
}

from bottle import request
from pip_services3_rpc.services import RestService


class MyRestService(RestService):

    def __init__(self):
        super(MyRestService, self).__init__()
        self._base_route = "/my_service"

    def my_page(self, name):
        result = f"{request.query.get('message')}, {name}"
        return self.send_result(result)

    def register(self):
        self.register_route(method="GET", route="/my_page/<name>", schema=None, handler=self.my_page)


from pip_services3_commons.config import ConfigParams

my_rest_service = MyRestService()

my_rest_service.configure(ConfigParams.from_tuples("connection.protocol", "http",
                                                   "connection.host", "localhost",
                                                   "connection.port", 15239))

my_rest_service.open("123")

Not available

Running our REST service

With our REST service complete, we can now proceed to run it.To see the result of our code, we use the following URL:

http://localhost:15239/my_service/my_page/John?message=hello

Which should display “Hello John” on our browser

figure 2

Wrapping up

In this tutorial, we have seen how to create a simple REST service using the RestService component available in the Pip.Services toolkit, RPC module, services library. First, we created our service class. Then, we configured and run it. Finally, the result was shown as a page on our browser.