Nancy.RestModule is designed to create REST resources in a fast and simple way with NancyFx. The RestModule decouples the NancyModule from your self-implemented controller, so the controller can be tested easily.
Nancy.RestModule can handle DELETE, GET, POST and PUT requests and provides a simple JSON.
With the generic request handlers you are able to define your API interface by simple RequestModels which are bind automatically from NancyFx.
Install via nuget https://www.nuget.org/packages/Nancy.RestModule
PM> Install-Package Nancy.RestModule
-
Create your
RestModulein your NancyFx-Application.public class CustomerModule : RestModule { public CustomerModule() : base("/customer") { } }
-
Create your custom
Controllerand register it to theDIContainer. Now theControllercan be easily tested withUnitTestswithoutNancy.Testingpublic class CustomerController : ICustomerController { private readonly ICustomerService _service; public CustomerController(ICustomerService service) { _service = service; } public ResponseModel GetList() { IEnumerable<ICustomer> customers = _service.FindAll(); return customers.CreateResponse(); } public ResponseModel Get(GetCustomerRequest customerRequest) { ICustomer customer = _service.Find(customerRequest.Id); return customer.CreateResponse(); } // ... etc. }
-
Inject the controller in the module and define your routes and models. Now you can define your REST interface without pushing everything in the
NancyModule.public class CustomerModule : RestModule { public CustomerModule(ICustomerController controller) : base("/customer") { GetHandler("/", controller.GetList); GetHandler<GetCustomerRequest>("/{id}", controller.Get); PostHandler<PostCustomerRequest>("/", controller.Post); PutHandler<PutCustomerRequest>("/{id}", controller.Put); } }
Compile, run and enjoy the simplicity!
In the repository you can find Nancy.RestModule.Demo which is a simple demo to show how to use Nancy.RestModule.
- Compile and run the demo application.
- Now you can list all customers and should get the following response.
[ { "id": <Guid>, "firstName": "Jeff", "lastName": "Dunham", "age": 56, "created": <current datetime> }, { "id": <Guid>, "firstName": "Lee", "lastName": "Evans", "age": 53, "created": <current datetime> }, { "id": <Guid>, "firstName": "John", "lastName": "Cleese", "age": 79, "created": <current datetime> } ] (Optional)Change the resource withPUTandPOST
Copyright © 2017 Sean Roddis
Nancy.RestModule is licensed under MIT. Refer to license.txt for more information.