Edit on GitHub

Why ServiceStack

Developed in the modern age, ServiceStack provides an alternate, cleaner POCO-driven way of creating web services.

  • Simplicity
  • Speed
  • Web Services Best Practices
  • Message-based Services - Model-driven, code-first, friction-free development
  • Native Clients - Clean, end-to-end typed idiomatic APIs for most major platforms
  • Modern - No XML config, IOC built-in, no code-gen, conventional defaults
  • Smart - Infers greater intelligence from your strongly typed DTOs
  • Effortless Features - Most features enhance your existing DTOs making them trivial to enable
  • Multi Platform - Supports .NET 4.5 and .NET Core platforms for hosting on Windows, OSX, Linux
  • Multiple Hosts - Run in Web, Console, native Windows/OSX Desktop Apps, Windows Services
  • Host Agnostic - Services are decoupled from HTTP and can be hosted in MQ Services
  • Highly testable - Typed, idiomatic client APIs enable succinct, intuitive Integration tests
  • Mature - Stable with over 8+ years of development
  • Preserve Investment - modern libraries that are Continuously Improved (not abandoned or replaced)
  • Dependable - Commercially supported and actively developed

Features Overview

ServiceStack is a simple, fast, versatile and highly-productive full-featured Web and Web Services Framework that’s thoughtfully-architected to reduce artificial complexity and promote remote services best-practices with a message-based design that allows for maximum re-use that can leverage an integrated Service Gateway for the creation of loosely-coupled Modularized Service Architectures. ServiceStack Services are consumable via an array of built-in fast data formats (inc. JSON, XML, CSV, JSV, ProtoBuf, Wire and MsgPack) as well as XSD/WSDL for SOAP endpoints and Rabbit MQ, Redis MQ and Amazon SQS MQ hosts.

Its design and simplicity focus offers an unparalleled suite of productivity features that can be declaratively enabled without code, from creating fully queryable Web API’s with just a single Typed Request DTO with Auto Query supporting every major RDBMS to the built-in support for Auto Batched Requests or effortlessly enabling rich HTTP Caching and Encrypted Messaging for all your existing services via Plugins.

Your same Services also serve as the Controller in ServiceStack’s Smart Razor Views reducing the effort to serve both Web and Single Page Apps as well as Rich Desktop and Mobile Clients that are able to deliver instant interactive experiences using ServiceStack’s real-time Server Events.

ServiceStack Services also maximize productivity for consumers providing an instant end-to-end typed API without code-gen enabling the most productive development experience for developing .NET to .NET Web Services.

Generate Instant Typed APIs from within all Major IDEs!

ServiceStack now integrates with all Major IDE’s used for creating the best native experiences on the most popular platforms to enable a highly productive dev workflow for consuming Web Services, making ServiceStack the ideal back-end choice for powering rich, native iPhone and iPad Apps on iOS with Swift, Mobile and Tablet Apps on the Android platform with Java, OSX Desktop Appications as well as targetting the most popular .NET PCL platforms including Xamarin.iOS, Xamarin.Android, Windows Store, WPF, WinForms and Silverlight:

VS.NET integration with ServiceStackVS

Providing instant Native Typed API’s for C#, TypeScript, F# and VB.NET directly in Visual Studio for the most popular .NET platforms including iOS and Android using Xamarin.iOS and Xamarin.Android on Windows.

Xamarin Studio integration with ServiceStackXS

Providing C# Native Types support for developing iOS and Android mobile Apps using Xamarin.iOS and Xamarin.Android with Xamarin Studio on OSX. The ServiceStackXS plugin also provides a rich web service development experience developing Client applications with Mono Develop on Linux

Xcode integration with ServiceStackXC Plugin

Providing an instant Native Typed API in Swift including generic Service Clients enabling a highly-productive workflow and effortless consumption of Web Services from native iOS and OSX Applications - directly from within Xcode!

Android Studio integration with ServiceStackIDEA

Providing an instant Native Typed API in Java and Kotlin including idiomatic Java Generic Service Clients supporting Sync and Async Requests by levaraging Android’s AsyncTasks to enable the creation of services-rich and responsive native Java or Kotlin Mobile Apps on the Android platform - directly from within Android Studio!

IntelliJ integration with ServiceStackIDEA

The ServiceStack IDEA plugin is installable directly from IntelliJ’s Plugin repository and enables seamless integration with IntelliJ Java Maven projects for genearting a Typed API to quickly and effortlessly consume remote ServiceStack Web Services from pure cross-platform Java or Kotlin Clients.

Eclipse integration with ServiceStackEclipse

The unmatched productivity offered by Java Add ServiceStack Reference is also available in the ServiceStackEclipse IDE Plugin that’s installable from the Eclipse MarketPlace to provide deep integration of Add ServiceStack Reference with Eclipse Java Maven Projects enabling Java Developers to effortlessly Add and Update the references of their evolving remote ServiceStack Web Services.

servicestack-cli - Simple command-line utilities for ServiceStack

In addition to our growing list of supported IDE’s, the servicestack-cli cross-platform command-line npm scripts makes it easy for build servers, automated tasks and command-line runners of your favorite text editors to easily Add and Update ServiceStack References!

Simple Customer Database REST Services Example

This example is also available as a stand-alone integration test:

//Web Service Host Configuration
public class AppHost : AppSelfHostBase
{
    public AppHost() 
        : base("Customer REST Example", typeof(CustomerService).Assembly) {}

    public override void Configure(Container container)
    {
        //Register which RDBMS provider to use
        container.Register<IDbConnectionFactory>(c => 
            new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));

        using (var db = container.Resolve<IDbConnectionFactory>().Open())
        {
            //Create the Customer POCO table if it doesn't already exist
            db.CreateTableIfNotExists<Customer>();
        }
    }
}

//Web Service DTO's
[Route("/customers", "GET")]
public class GetCustomers : IReturn<GetCustomersResponse> {}

public class GetCustomersResponse
{
    public List<Customer> Results { get; set; } 
}

[Route("/customers/{Id}", "GET")]
public class GetCustomer : IReturn<Customer>
{
    public int Id { get; set; }
}

[Route("/customers", "POST")]
public class CreateCustomer : IReturn<Customer>
{
    public string Name { get; set; }
}

[Route("/customers/{Id}", "PUT")]
public class UpdateCustomer : IReturn<Customer>
{
    public int Id { get; set; }

    public string Name { get; set; }
}

[Route("/customers/{Id}", "DELETE")]
public class DeleteCustomer : IReturnVoid
{
    public int Id { get; set; }
}

// POCO DB Model
public class Customer
{
    [AutoIncrement]
    public int Id { get; set; }

    public string Name { get; set; }
}

//Web Services Implementation
public class CustomerService : Service
{
    public object Get(GetCustomers request)
    {
        return new GetCustomersResponse { Results = Db.Select<Customer>() };
    }

    public object Get(GetCustomer request)
    {
        return Db.SingleById<Customer>(request.Id);
    }

    public object Post(CreateCustomer request)
    {
        var customer = new Customer { Name = request.Name };
        Db.Save(customer);
        return customer;
    }

    public object Put(UpdateCustomer request)
    {
        var customer = Db.SingleById<Customer>(request.Id);
        if (customer == null)
            throw HttpError.NotFound("Customer '{0}' does not exist".Fmt(request.Id));

        customer.Name = request.Name;
        Db.Update(customer);

        return customer;
    }

    public void Delete(DeleteCustomer request)
    {
        Db.DeleteById<Customer>(request.Id);
    }
}

Calling the above REST Service from any C#/.NET Client

No code-gen required, can re-use above Server DTOs:

var client = new JsonServiceClient(BaseUri);

//GET /customers
var all = client.Get(new GetCustomers());                         // Count = 0

//POST /customers
var customer = client.Post(new CreateCustomer { Name = "Foo" });

//GET /customer/1
customer = client.Get(new GetCustomer { Id = customer.Id });      // Name = Foo

//GET /customers
all = client.Get(new GetCustomers());                             // Count = 1

//PUT /customers/1
customer = client.Put(
    new UpdateCustomer { Id = customer.Id, Name = "Bar" });       // Name = Bar

//DELETE /customers/1
client.Delete(new DeleteCustomer { Id = customer.Id });

//GET /customers
all = client.Get(new GetCustomers());                             // Count = 0

Same code also works with PCL Clients in Xamarin iOS/Android, Windows Store Apps

F# and VB.NET can re-use same .NET Service Clients and DTO’s

Calling from TypeScript

const client = new JsonServiceClient(baseUrl);

client.get(new GetCustomers())
    .then(r => {
        const results = r.results;
    });

Calling from Swift

let client = JsonServiceClient(baseUrl: BaseUri)

client.getAsync(GetCustomers())
    .then {
        let results = $0.results;
    }

Calling from Java

JsonServiceClient client = new JsonServiceClient(BaseUri);

GetCustomersResponse response = client.get(new GetCustomers());
List<Customer> results = response.results; 

Calling from Kotlin

val client = JsonServiceClient(BaseUri)

val response = client.get(GetCustomers())
val results = response.results

Calling from jQuery using TypeScript Defintions

$.getJSON($.ss.createUrl("/customers", request), request, 
    function (r: dtos.GetCustomersResponse) {
    	alert(r.Results.length == 1);
    });

Calling from jQuery

$.getJSON(baseUri + "/customers", function(r) {
	alert(r.Results.length == 1);
});

Calling the from Dart JsonClient

var client = new JsonClient(baseUri);
client.customers()
	.then((r) => alert(r.Results.length == 1)); 

That’s all the application code required to create and consume a simple database-enabled REST Web Service!

Define web services following Martin Fowlers Data Transfer Object Pattern

ServiceStack was heavily influenced by Martin Fowlers Data Transfer Object Pattern:

When you’re working with a remote interface, such as Remote Facade (388), each call to it is expensive. As a result you need to reduce the number of calls, and that means that you need to transfer more data with each call. One way to do this is to use lots of parameters. However, this is often awkward to program - indeed, it’s often impossible with languages such as Java that return only a single value.

The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across the connection. Usually an assembler is used on the server side to transfer data between the DTO and any domain objects.

The Request- and Response DTO’s used to define web services in ServiceStack are standard POCO’s while the implementation just needs to inherit from a testable and dependency-free IService marker interface. As a bonus for keeping your DTO’s in a separate dependency-free .dll, you’re able to re-use them in your C#/.NET clients providing a strongly-typed API without any code-gen what-so-ever. Also your DTO’s define everything ServiceStack does not pollute your web services with any additional custom artefacts or markup.

Multiple pluggable Formats

ServiceStack re-uses the custom artefacts above and with zero-config and without imposing any extra burden on the developer adds discoverability and provides hosting of your web service on a number of different formats, including:

Multiple Endpoints

Whilst ServiceStack is fundamentally a premier HTTP Framework, its Services can also be consumed from SOAP 1.1 and 1.2 endpoints as well as a number of MQ Servers:

Multiple Hosting Options

In addition to supporting multiple formats and endpoints, ServiceStack can also be hosted within a multitude of differeint hosting options:

VS.NET Templates

There’s a VS.NET Template for creating solutions targeting most of the above platforms.

E.g. the React Desktop Apps VS.NET Template provides an easy and integrated way to host a Single Page React App on multiple platforms.

WCF the anti-DTO Web Services Framework

Unfortunately this best-practices convention is effectively discouraged by Microsoft’s WCF SOAP Web Services framework as they encourage you to develop API-specific RPC method calls by mandating the use of method signatures to define your web services API. This results in less re-usable, more client-specific APIs that encourages more remote method calls.

Unhappy with this perceived anti-pattern in WCF, ServiceStack was born providing a Web Service framework that embraces best-practices for calling remote services, using config-free, convention-based DTO’s.

Encourages development of message-style, re-usable and batch-full web services

Entire POCO types are used to define the request- and response DTO’s to promote the creation well-defined coarse-grained web services. Message-based interfaces are best-practices when dealing with out-of-process calls as they can batch more work using less network calls and are ultimately more re-usable as the same operation can be called using different calling semantics. This is in stark contrast to WCF’s Operation or Service contracts which encourage RPC-style, application-specific web services by using method signatures to define each operation.

As it stands in general-purpose computing today, there is nothing more expensive you can do than a remote network call. Although easier for the newbie developer, by using methods to define web service operations, WCF is promoting bad-practices by encouraging them to design and treat web-service calls like normal function calls even though they are millions of times slower. Especially at the app-server tier, nothing hurts performance and scalability of your client and server than multiple dependent and synchronous web service calls.

Batch-full, message-based web services are ideally suited in development of SOA services as they result in fewer, richer and more re-usable web services that need to be maintained. RPC-style services normally manifest themselves from a client perspective that is the result of the requirements of a single applications data access scenario. Single applications come and go over time while your data and services are poised to hang around for the longer term. Ideally you want to think about the definition of your web service from a services and data perspective and how you can expose your data so it is more re-usable by a number of your clients.

Difference between an RPC-chatty and message-based API

public interface IWcfCustomerService
{
    Customer GetCustomerById(int id);
    List<Customer> GetCustomerByIds(int[] id);
    Customer GetCustomerByUserName(string userName);
    List<Customer> GetCustomerByUserNames(string[] userNames);
    Customer GetCustomerByEmail(string email);
    List<Customer> GetCustomerByEmails(string[] emails);
}

contrast with an equivalent message based service:

public class Customers : IReturn<List<Customer>> 
{
   public int[] Ids { get; set; }
   public string[] UserNames { get; set; }
   public string[] Emails { get; set; }
}

Any combination of the above can be fulfilled by 1 remote call, by the same single web service - i.e what ServiceStack encourages!

Fewer and more batch-full services require less maintenance and promote the development of more re-usable and efficient services. In addition, message APIs are much more resilient to changes as you’re able to safely add more functionality or return more data without breaking or needing to re-gen existing clients. Message-based APIs also lend them better for cached, asynchronous, deferred, proxied and reliable execution with the use of brokers and proxies.

Comparatively there is almost no win for a remote RPC API, except to maybe hide a remote service even exists by making a remote call look like a method call even though they’re millions of times slower, leading new developers to develop inefficient, brittle systems from the start.

Community Resources