Learn how to use the SDK in your backend to handle endpoints.
On this page, you will learn how to use the SDK with your back-end application. The tutorial uses Uniscale's Message Threads demo solution as its base. For more detailed information on the SDK, see Library implementation.
You can find similar complete code samples with running instructions in our GitHub for every language:
You can find a guide with correct SDK information for your generated languages in your solution or service's SDK Portal in Uniscale.
Implementing the endpoint logic
Your SDK is built with the endpoints that you have defined. In order to get started with your backend you will need to implement the logic of the endpoint and create an interceptor for it that you register inside PlatformSession.
In this sample, we will implement basic logic for GetOrRegister the endpoint. This endpoint will simply return the pre-generated sample data for return type. We then register that interceptor into an instance of a session, which can be injected/passed to our endpoint/controller.
For example, if we create ASP.NET Core WebAPI. We will need to add PlatformSession into services when building the WebApplication.
Program.cs
usingUniscale.Core;usingUniscale.Designtime;usingUniscaleDemo.Account_1_0.Functionality.ServiceToModule.Account.Registration.ContinueToApplication;usingUniscaleDemo.Account.Account;var builder =WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddSingleton<PlatformSession>(_ =>{returnPlatform.Builder() // Implement what happens on endpoints when GatewayRequests come in. .WithInterceptors(i => i .InterceptRequest(GetOrRegister.AllFeatureUsages,GetOrRegister.Handle((input, ctx) =>Result<UserFull>.Ok(UserFull.Samples().DefaultSample())))) .Build() .Result;});// ... Rest of your basic .NET scaffold / Initialize code
For example, creating a simple Quart backend app. We will need to initialize the Quart app and setup the PlatformSession with our interceptor logic before serving.
app.py
from typing import Optionalfrom quart import Quart, requestfrom quart_cors import corsfrom uniscale.core import ( Result, PlatformSession,)from uniscale.core.platform.platform import Platformfrom uniscale.uniscaledemo.account_1_0.functionality.servicetomodule.account.registration.continuetoapplication.get_or_register import ( GetOrRegister,)from uniscale.uniscaledemo.account.account.user_full import UserFull# Initialize Quart app.app =Quart(__name__)app =cors(app, allow_origin="*")# Define instances for builder and PlatformSessionbuilder = Platform.builder()session: Optional[PlatformSession]=None#initialize session with interceptors and other logic before serving@app.before_servingasyncdefsetup_session():global session session =await builder.with_interceptors(lambdai: i.intercept_request( GetOrRegister.all_feature_usages, GetOrRegister.handle(lambdacinput, ctx: Result.ok(UserFull.samples().default_sample()) ), ) ).build()# endpoint and app start in next sample
For example, if we were creating spring boot app with the web starter.
We will then initialize the express application. We will need to initialize the PlatformSession on startup and ensure it's usable in endpoints alter on.
// Start express server as you see fit. exportconststartServer= () => {constPORT=7156constapp=express()app.use(express.json())app.use(cors())// Endpoint comes here from next sampleapp.listen(PORT, () => {console.log(`Server is listening on port ${PORT}`) })}// On startup you will need to initialize the session with interceptorsconstapp=async () => {awaitinitializePlatformSession()startServer()}app()
To create a backend web application in PHP, you can use a framework like Laravel or a micro-framework like Slim. Here, we'll use Slim to keep it simple and straightforward.
First, install Slim and other necessary packages using Composer:
Then, create a server.php file to set up the Slim application and initialize the PlatformSession:
<?phprequire'vendor/autoload.php';usePsr\Http\Message\ResponseInterfaceas Response;usePsr\Http\Message\ServerRequestInterfaceas Request;useSlim\Factory\AppFactory;// Initialize the PlatformSessionPlatformSessionManager::initializePlatformSession();$app =AppFactory::create();// Middleware to parse JSON bodies$app->addBodyParsingMiddleware();// CORS Middleware$app->add(function (Request $request, $handler) { $response = $handler->handle($request);return $response->withHeader('Access-Control-Allow-Origin','*')->withHeader('Access-Control-Allow-Headers','X-Requested-With, Content-Type, Accept, Origin, Authorization')->withHeader('Access-Control-Allow-Methods','GET, POST, PUT, DELETE, PATCH, OPTIONS');});// Define a sample endpoint$app->post('/register',function (Request $request,Response $response) { $body = $request->getParsedBody(); $requestJson =json_encode($body); $result =PlatformSessionManager::$platformSession->acceptGatewayRequest($requestJson); $responseBody = $result->isSuccess()? ['userIdentifier'=> $result->getValue()->userIdentifier]: ['error'=> $result->getError()->toLongString()]; $response->getBody()->write(json_encode($responseBody));return $response->withHeader('Content-Type','application/json');});// Start the server$app->run();
This sets up a Slim application, initializes the PlatformSession, and defines a sample endpoint /register . The endpoint handles a POST request to register a user and returns the user identifier or an error message.
To run this script you will need to specify the host php -S localhost:8080 server.php
Now there is a server running with PlatformSession ready to be injected/passed.
Create network endpoint
With the server running and SDK endpoint logic implemented into your session, you're still missing the network endpoint. You will only need to be able to inject/pass an instance of PlatformSession into your controller/ network endpoint definition. Then inside your network endpoint, you need to pass the GatewayRequest JSON data into the session's acceptGatewayRequest function and return the output of that function in JSON.
Use the .toJson function of Result to avoid any serialization issues.
These endpoints can be created using any library or protocol that fits your needs. You'll just need to be able to pass the content. We will select a library for each language and showcase an example, but this does not mean it would only work with these showcased techniques.
For basic ASP.NET WebAPI, this means injecting the PlatformSession into your controller and creating a single HTTP endpoint that serves the app based on the created instance of PlatformSession.
GatewayController.cs
usingSystem.Text.Json;usingMicrosoft.AspNetCore.Mvc;usingUniscale.Core;// Sample implementation for demo. Please note that this is just one showcase// You are free to use your own protocols/libraries for this task.namespaceDemoApi.Controllers;[ApiController][Route("")]publicclassGatewayController:ControllerBase{ // Inject the PlatformSession into your controllerprivatereadonlyPlatformSession _session;publicGatewayController(PlatformSession session) { _session = session; } [HttpPost]publicasyncTask<string> Handle([FromBody]JsonElement request) { // All you need to do is pass json to session and parse result to json.var result =await_session.AcceptGatewayRequest(request.GetRawText());returnresult.ToJson(); }}
For our Quart app, this means defining the single endpoint route using the PlatformSession. And then simply starting the app.
app.py
# Sample implementation for demo. Please note that this is just one showcase# You are free to use your own protocols/libraries for this task.@app.route("/", methods=["POST"])asyncdefhandle_request():# All you need to do is pass json to session and parse result to json. data =await request.get_data() result =await session.accept_gateway_request(data)return result.to_json()if__name__=="__main__": app.run(port=7156)
For basic Spring Boot API, this means injecting the PlatformSession into your controller and creating a single HTTP endpoint that serves the app based on the created instance of PlatformSession.
GatewayController.java
packagecom.example.demo;importcom.uniscale.sdk.core.PlatformSession;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.ResponseBody;// Sample implementation for demo. Please note that this is just one showcase// You are free to use your own protocols/libraries for this task.@ControllerpublicclassGatewayController {privatefinalPlatformSession session;publicGatewayController(PlatformSession session) {this.session= session; } @PostMapping("") @ResponseBodypublicStringhandle(@RequestBodyString request) {// All you need to do is pass json to session and parse result to json.returnthis.session.acceptGatewayRequest(request).join().toJson(); }}
For basic express API, this means matching all routes and creating a single HTTP endpoint that serves the app based on the created instance of PlatformSession.
// Sample implementation for demo. Please note that this is just one showcase// You are free to use your own protocols/libraries for this task.app.all("/",async (req, res) => {constrequest=req.body asBackendAction<unknown,unknown>// All you need to do is pass json to session and parse result to json.try {constvalue=awaitplatformSession.acceptGatewayRequest(JSON.stringify(request), )res.status(200).send(value.toJson()) } catch (error) {console.error(error)res.status(500).send(error) }})
Here's a PHP sample that you can add to server.php before $app->run();. It matches all routes and creates a single HTTP endpoint that serves the app based on the created instance of PlatformSession:
// Match all routes and create a single HTTP endpoint$app->any('/',function (Request $request,Response $response) { $body = $request->getParsedBody(); $requestJson =json_encode($body);try { $value =PlatformSessionManager::$platformSession->acceptGatewayRequest($requestJson); $responseBody = $value->toJson(); $response->getBody()->write($responseBody);return $response->withHeader('Content-Type','application/json')->withStatus(200); } catch (Exception $e) {error_log($e->getMessage()); $response->getBody()->write(json_encode(['error'=> $e->getMessage()]));return $response->withHeader('Content-Type','application/json')->withStatus(500); }});
This code defines a single endpoint that matches all routes. The endpoint processes the incoming request, passes it to the PlatformSession, and returns the result as JSON. If an error occurs, it logs the error and returns a 500 status with the error message.
With just a couple of steps like that, we have created a backend that can be easily called with a front-end client that was created based on Front-end with Uniscale SDK.