Functional

Live on this server

Uses delegates to implement a web service, similar to ASP.NET Core Minimal APIs.

FunctionalSample.cs60 lines
using GenHTTP.Api.Content;
using GenHTTP.Api.Protocol;

using GenHTTP.Modules.Functional;
using GenHTTP.Modules.Layouting;

public static class FunctionalSample
{

    public static IHandlerBuilder Create()
    {
        /*
         *
         * Shows how to use delegates that will be invoked
         * to handle incoming HTTP requests.
         *
         * See https://genhttp.org/documentation/content/frameworks/functional/
         *
         */

        var books = new List<Book>()
        {
            new(1, "Lord of the Rings")
        };

        var service = Inline.Create()
                            .Get(() => // GET /samples/functional/books/
                            {
                                lock (books) return books.ToList();
                            })
                            .Put((Book book) => // PUT /samples/functional/books/ with JSON/XML/... payload
                            {
                                lock (books)
                                {
                                    if (books.Count >= 50)
                                    {
                                        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(":id", (int id) => // DELETE /samples/functional/books/1
                            {
                                lock (books) return books.RemoveAll(b => b.Id == id);
                            });

        return Layout.Create()
                     .Add("books", service);
    }

    public record Book(int Id, string Title);

}

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.

  1. List all books

    GET
    curl -i 'https://genhttp.org/samples/functional/books/'
  2. Add a book

    PUT
    Headers and body
    curl -i -X PUT -H 'Content-Type: application/json' -d '{ "title": "The Hobbit" }' 'https://genhttp.org/samples/functional/books/'
  3. Delete a book

    DELETE
    Headers and body
    curl -i -X DELETE 'https://genhttp.org/samples/functional/books/1'