CTS – Your Technology Partner

Getting Started with ServiceStack Part 3

Written by Lydon Bergin on May 15, 2014

 

Creating a Web API using ServiceStack

Introduction

In Part 1 of this blog post, we installed and configured the ServiceStack Web Services Framework and ServiceStack OrmLite. In Part 2 we created a simple data access layer using ServiceStack’s OrmLite ORM. In this third and final post, we will create some web services that use our data access layer to create a full Web API for our Person class!

Create Request Objects

The ServiceStack Web Services Framework is built around the DTO (Data Transfer Object) Pattern which follows the familiar Request > Process > Response flow. ServiceStack will handle the capturing of each request and pass it to the correct service for processing, and the service will return a response object to the client. Using ServiceStack, requests are simple classes with public properties that represent expected input data.

Create a new file in your solution called “Requests.cs” like below:

namespace ServiceStack.QuickStart

{

    [Route(“/Person”, Verbs =“GET”)]

    publicclassGetPeopleRequest { }

 

    [Route(“/Person”, Verbs =“POST”)]

    [Route(“/Person/PersonID”, Verbs =“PUT”)]

    publicclassPersonRequest

    {

        publicint PersonID { get; set; }

        publicstring FirstName { get; set; }

        publicstring LastName { get; set; }

        publicstring EmailAddress { get; set; }

    }

 

    [Route(“/Person/{PersonID}”, Verbs =“GET, DELETE”)]

    publicclassPersonIDRequest

    {

        publicint PersonID { get; set; }

    }

}

Note that I combined these three classes into a single file, but in practice, these should be separated into their own class files and added to a namespace like “Requests”.

The [Route] annotation tells ServiceStack which Routes or URL’s should accept our request types and which HTTP Verbs to accept on those routes.

One of the main strengths of ServiceStack is the ability to reuse both request and POCO classes throughout the framework. For further information about the three request classes, see the table below:

GetPeopleRequest

This is an empty request since no input parameters are needed.

PersonRequest

This request accepts all fields that we added to our Person class and is used to both Add and Update our Person objects.

PersonIDRequest

This request accepts PersonID as an integer and will be used to return a single Person by ID as well as to Delete a Person.

Even in this simple case, two of our three requests have been utilized for multiple operations!

Create the Service

We are now ready to create our service class and finally see the power that ServiceStack gives us!

Create a new class in your solution called “PersonService” like below:

using System.Collections.Generic;

 

namespace ServiceStack.QuickStart

{

    /// <summary>

    /// The PersonService inherits from ServiceStack.Service and provides the

    /// processing to the incoming request objects.  In this service we’re returning

    /// types we have reused, but you can create your own response objects to return as well.

    /// Note that the Method names must match the HTTP Verb that they are meant to handle.

    /// </summary>

    publicclassPersonService : Service

    {

        // Returns a list of people to the user given a GetPeopleRequest (which is empty)

        publicList<Person> Get(GetPeopleRequest request)

        {

            // Notice we’re passing “Db” as a parameter to PersonDataProvider,

            // this Db variable is provided by the IOC Container we set up in

            // the ApplicationHost.Configure method.

            PersonDataWorker pdp =newPersonDataWorker(Db);

            return pdp.GetPeopleList();

        }

 

        // Return a single person given their PersonID

        publicPerson Get(PersonIDRequest request)

        {

            PersonDataWorker pdp =newPersonDataWorker(Db);

            return pdp.GetPersonByID(request.PersonID);

        }

 

        // Creates a new Person

        publicint Post(PersonRequest request)

        {

            var p =newPerson()

            {

                FirstName = request.FirstName,

                LastName = request.LastName,

                EmailAddress = request.EmailAddress

            };

 

            PersonDataWorker pdp =newPersonDataWorker(Db);

            return pdp.AddPerson(p);

        }

 

        // Updates an existing person

        publicPerson Put(PersonRequest request)

        {

            var p =newPerson()

            {

                ID = request.PersonID,

                FirstName = request.FirstName,

                LastName = request.LastName,

                EmailAddress = request.EmailAddress

            };

 

            PersonDataWorker pdp =newPersonDataWorker(Db);

            return pdp.UpdatePerson(p);

        }

 

        // Deletes a person

        publicvoid Delete(PersonIDRequest request)

        {

            PersonDataWorker pdp =newPersonDataWorker(Db);

            pdp.DeletePersonByID(request.PersonID);

        }

    }

}

Two important things to note from the code above are that the method names match the HTTP Verbs from our Requests.cs file, and the use of our PersonDataWorker class, which we are passing the Db object. The Service class that the PersonService inherits implements the Db object and it was automatically wired when we registered the IDbConnectionFactory in the ApplicationHost.Configure method. We pass the Db object (an IDbConnection) into our PersonDataWorker’s constructor so that the data worker can safely use the database connection.

Testing the Web Services

We are finally ready to test the services and see what ServiceStack has done for us. Run the application and you will once again see the ServiceStack metadata page, but now we have a list of operations that map to the PersonService.

image

ServiceStack automatically creates endpoints and interfaces for multiple content types including XML & JSON, and additional content types can be added using NuGet. Click on the JSON link under GetPeopleRequest and ServiceStack will provide you with sample requests and responses.

image

Now navigate to the /person route of your web application and you will see the sample data we created in Part 1!

image

Notice that even though we did not create any views or, in fact, any user interfaces at all, ServiceStack has created one for us. In Addition, we can view this data in multiple formats simply by clicking the json or xml links below, as well as by simply adding an extension to the URL like below:

image

Conclusion:

In this series of blog posts, we used the ServiceStack Web Services Framework in conjunction with ServiceStack’s OrmLite to create a fully featured Web API with minimal configuration and very little code. The ServiceStack libraries are an excellent alternative to Microsoft’s Web API and Entity Framework for building a feature-rich API based on remote services best practices.

Comments

comments