Webservices
Live on this serverImplements a REST webservice via a handler class.
using GenHTTP.Api.Content;
using GenHTTP.Api.Protocol;
using GenHTTP.Modules.Controllers;
using GenHTTP.Modules.Layouting;
using GenHTTP.Modules.Reflection;
using GenHTTP.Modules.Webservices;
public static class WebserviceSample
{
public static IHandlerBuilder Create()
{
/*
*
* Shows how to declare and register a class that will be invoked
* to handle incoming HTTP requests.
*
* See https://genhttp.org/documentation/content/frameworks/webservices/
*
*/
return Layout.Create()
.AddService<BookService>("books");
}
public record Book(int Id, string Title);
public class BookService
{
private const int MaxBooks = 50;
private static readonly List<Book> Books =
[
new(1, "Lord of the Rings")
];
// GET /samples/webservices/books/
[ResourceMethod]
public List<Book> List()
{
lock (Books) return [..Books];
}
// PUT /samples/webservices/books/ with JSON/XML/... payload
[ResourceMethod(Method.Put)]
public Book Create(Book book)
{
lock (Books)
{
if (Books.Count >= MaxBooks)
{
throw new ProviderException(ResponseStatus.Conflict, "The shelf is full, please delete a book first");
}
var toAdd = book with
{
Id = Books.Select(b => b.Id).DefaultIfEmpty().Max() + 1
};
Books.Add(toAdd);
return toAdd;
}
}
// DELETE /samples/webservices/books/1
[ResourceMethod(Method.Delete, ":id")]
public void Delete([FromPath] int id)
{
lock (Books) Books.RemoveAll(b => b.Id == id);
}
}
}Try it
Send the requests to the sample running on this server - change the path, headers or body as you like, or copy them as curl commands.
List all books
curl -i 'https://genhttp.org/samples/webservices/books/'Add a book
curl -i -X PUT -H 'Content-Type: application/json' -d '{ "title": "The Hobbit" }' 'https://genhttp.org/samples/webservices/books/'Delete a book
curl -i -X DELETE 'https://genhttp.org/samples/webservices/books/1'