Custom Endpoints

From SocialStack
Revision as of 11:46, 30 April 2025 by 2a02:c7c:c489:9900:86:b433:6f70:6262 (talk) (→‎TypeScript bindings)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

When you generate a new API content type, it will by default come with a controller based on AutoController which handles the typical CRUD functionality (create, delete, list, get etc). It is however often convenient to add additional custom endpoints to your controllers.

Getting started

All endpoints can potentially be accessed via the web API, websocket API or by being directly mounted by the serverside renderer. Because there are 3 entry routes, controller methods in socialstack are wrapped so that you only need to write one and it will be available to all 3 routes by default. This does mean, however, that your endpoint cannot use HttpRequest or HttpContext unless you know it is an endpoint which will only be needed in the web API and nowhere else.

So, to create an endpoint, start by adding a method inside any *Controller.cs file. These controller files are also partial so if you're adding custom endpoints to built in controllers, such as UserController.cs, you can create a partial class to extend it without breaking upgradeability. Mark your method with one or more ASP.NET Http method attribute which tells the routing that this is a public endpoint and what its URL will be in the web API. For all API endpoints the resulting URL will always be lowercase.

// accessed via {controllerRoute}/helloworld
[HttpGet("helloWorld")]
public string HelloWorld()
{
    return "hello, world!";
}

Associated services

In SocialStack, controllers are singletons. You can use dependency injection in your controller constructors to pull in any services you need, however, it is generally recommended to put logic inside your service (along with any services it depends on) and then invoke it instead. This is because it makes your functionality easily accessible to other services. Controllers then just primarily have the job of mapping from the public APIs to your internal service methods. If your controller originated from creating a new content type, then the service for that content type is already available as a field called _service. If for any reason you can't use dependency injection, then Services.Get<XService>(); can always be used.

API Context

Almost all functionality in the API uses the Context object which tells you about the current user, their locale, their role etc. To obtain this object, simply add it as a parameter and it will be provided to you.

// accessed via {controllerRoute}/helloworld
[HttpGet("helloWorld")]
public string HelloWorld(Context context)
{
    return "hello, world!";
}

Return types

Returning null

Return a null to get a 404 response on the web API and equivalent behaviour on the serverside renderer. If your return type is a value type, you can still achieve this by returning it as a nullable.

Content objects

If your controller returns an object which ultimately derives from Content<> then your controller method will implicitly support includes and on the web API, the response will be in the {"result": ..} format with all necessary role specific field visibility rules being taken care of automatically.

Failure conditions

If your code throws an unexpected exception, the response on the web API will be a 500 and the error itself will only appear on the internal server log. If you throw a PublicException specifically, then the message inside your exception will be sent to the end user. A PublicException is able to set specific response codes as well and will typically be in the 4xx range as they imply the user did something wrong. As always though, you should not use exceptions as part of your common control flow: if you need an uncommon 2xx status code, don't throw an error to get it to happen and instead create a web only method.

ContentStream

The socialstack API is as non-allocating as possible, and this includes in its response streams. In order to avoid allocating and returning any sort of array or list, multiple content items can instead be streamed via the ContentStream type. Note that they must be content types specifically. As with singular content objects you can use includes automatically on any endpoint which returns a ContentStream, and as ContentStream is a value type, you can achieve a 404 response with a nullable `ContentStream<..>?` and then returning null when necessary.

FileContent

If you need to specify a mime type and some non-JSON payload, you can return a FileContent. This is typically used to return the pages themselves as well as precompressed CSS and so-on. As FileContent is a value type, you can achieve a 404 response with a nullable `FileContent?` and return null when necessary.

All other types

Anything else is serialised to JSON automatically. If you need something other than this behaviour, see the web only methods section below.

Web only methods

If you need something from the HttpRequest or you need to set something in to the HttpResponse, then you can use either as a parameter or the HttpContext itself.

// accessed via {controllerRoute}/helloworld
[HttpGet("helloWorld")]
public string HelloWorld(Context context, HttpRequest request)
{
    // request.Headers..

    return "hello, world!";
}

As these methods are web API only and cannot be used by the serverside renderer, they should generally be quite rare and you should favour using the common general use controller format as much as possible.

TypeScript bindings

When your API starts up, all controller methods - including any custom ones - will have typescript bindings automatically generated in the TypeScript/Api directory. You should commit these files such that any automated build has all the files it needs. These bindings are also compatible with the serverside renderer unless the endpoint is a web only one. For this reason you should always use them instead of using any of the methods inside the webRequest module directly as the serverside renderer does not make web requests to itself and thus any attempt to do so would fail.

For more information on how to use these, see the Public API.