Serving json from Matrix


(Mitch Kerry) #1

Hi

Was wondering if there was a way to use Matrix as an API end point to serve json that is ingested by another site?
It would need to be a secure key pair transaction.

Is this possible?
Thanks


(Peter McLeod) #2

Hi

yeah, there are are few ways you can do it just using standard Matrix assets:

Create a design to apply to whatever asset will act as your endpoint to serve JSON:

<MySource_PRINT id_name="__global__" var="content_type" content_type="application/json" /><MySource_AREA id_name="page_body" design_area="body" />

You could use a variety of assets to collate/generate the data (listings, searches etc) and format it as JSON.

If the key validation is just for a limited number of keys, then you could use matrix condition or server side js to validate.

For example a very simple setup might look something like:

Standard Page Asset (as endpoint, with JOSN design applied to it. Can set the webpath to something like, ‘example.json’)

The content container would be raw/raw html. Using server side JS to control the output you could grad the data from any number of places, transform it based on additional parameters in the request, clean it etc before printing to as the JSON to be returned.

Server side JS:

<script runat="server">
   var key =  "%globals_get_key%";
   var validKeys = ["23523525","78956795","07860558"];
   if (validKeys.indexOf(key) === -1) {
   		print('{"error":"Error message"}');
   } else {
 
   		var output = %globals_asset_contents_raw:1234%;
   		print(JSON.stringify(output));
   }
</script>

Thanks
Peter


(Mitch Kerry) #3

Thanks Peter

I’ll give that a try.

Mitch


(Mitch Kerry) #4

Hi Peter

Sorry, just on this…will it work if my version doesn’t support server side js?

thanks
Mitch


(Peter McLeod) #5

Hi

You don’t need to use server side JS, could use something along the lines of:

%begin_globals_get_key^eq:23523525%
	%globals_asset_contents_raw:1234%
%else_globals%
	{"error":"Error message"}
%end_globals%

Or for multiple possible keys you could store them in metadata somewhere as text (23523525,78956795,07860558):

%begin_asset_metadata_keys^explode:,^in_array:{globals_get_key}%
	%globals_asset_contents_raw:1234%
%else_asset%
	{"error":"Error message"}
%end_asset%

Thanks
Peter


(Mitch Kerry) #6

Awesome…thanks
Should work fine.