Tech Tip: Send JSON Data Using REST API with ORDA
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: November 21, 2019
4D can act as a powerful backend to complement almost any web application. Here is an example of how to build a simple REST API with ORDA that fetches an index of records and sends a JSON repsonse.
In this example, suppose we want to get data for all products in a Products table. First, in the On Web Connection method, we want to filter API requests for Products with an API namespace for Products:
// On Web Connection C_TEXT($1;$2;$url;$header) $url:=$1 $header:=$2 Case of : ($url="/api/products") PRODUCTS_API($header) // ...insert additional API request cases here... End case |
The PRODUCTS_API method will take in one parameter, the HTTP header and body, which contains the HTTP request method. We can filter for GET requests by checking if the HTTP header starts with "GET".
// PRODUCTS_API C_TEXT($1;$httpMethod) $httpMethod:=$1 Case of : ($httpMethod="GET@") SEND_PRODUCTS_JSON // ...insert additional HTTP request method cases here... End case |
The SEND_PRODUCTS_JSON method will query for all entities in the Products table, convert the entity selection into a collection and then into JSON. Finally, it will send the JSON back as a response.
// SEND_PRODUCTS_JSON C_OBJECT($json;$entitySelection) $entitySelection:=ds.Products.all() $json:=JSON Stringify($entitySelection.toCollection();*) WEB SEND TEXT($json;"application/json") |
Now, if we check /api/products, we should get a collection of JSON objects, each object representing a product entity.
Of course, the preceding methods can be modified and expanded on to include multiple cases for additional API requests and also for additional resources.