How can I create API with my custom code in Azure? - azure-api-management

Can I create an API that has the definition of the sum of two numbers and returns me the output. I want to write all the logic in Azure Web API Management itself. Is there any provision, or do I need to create it in my machine and import it to Azure Web API Management?
Is it possible to create it in Web API in Azure itself, rather than importing it?

There are two ways to go about this. APIM does support policy expressions: https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions This allows you to plug in arbitrary code into request processing pipeline. You can check policy samples here: https://learn.microsoft.com/en-us/azure/api-management/policy-samples to see this in action. When combined with other policies it does allow you to a lot of things. If we assume that you "addition" operation has URI template of /add?a={a}&b={b} then you can sum up and return result with one simple policy:
<return-response>
<set-status code="200" reason="OK" />
<set-body>#{
var a = int.Parse(context.Request.Url.Query.GetValueOrDefault("a", "0"));
var b = int.Parse(context.Request.Url.Query.GetValueOrDefault("b", "0"));
return (a + b).ToString();
}</set-body>
</return-response>
As you can see this is a pretty much regular C# code, but it's limited in what you can do and what types you can use (see first link). If you can't make it work within these limitations your best bet is to move custom logic outside of APIM, into Azure Functions, for example.

Related

Can we receive webhooks from Foundry when a dataset updates?

Can Foundry we receive Webhook calls to an arbitrary external endpoint when a dataset updates (e.g. new transaction committed, or jobspec updated)?
I checked around and couldn't find any hooks, maybe there is something at actions level, but that is downstream from transactions.
Alternatively you can workaround it by having a downstream transform that just exists to build once upstream has transactions, and use it to make said http requests from your transforms via the driver. I understand it's not the same as you requested, but it's the best workaround I can think of.
You'll have to request via your support to have whatever endpoint you want white listed within Foundry Configuration. This will likely have to be applied by Palantir, and it will raise security questions, so you should reach out internally via your support mechanisms.
Once you do that, something like this should work.
import requests
#transform_df(
_noop_df=Input("your upstream"),
Output("output dataset"))
def transform(_noop_df):
req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
# write the result of the request into the output if you want.

wsdl for JSON returned REST services

I'm new to REST Web based services and trying to understanding how the contract is created for JSON returned REST services.
From my understanding, any XML based SOAP/REST services will have a WSDL document.
What document is created for JSON based REST Services?
a REST web service doesn't have any auto explanation document like wsdl, you need to know how the webservice works, reading the documentation provided with it. Generally it works with common requests. Assuming that you have a products REST webservice, you could have:
GET /products -> read all products
GET /products/1 -> read the product 1
POST /products -> create a new product
PUT /products/1 -> update product 1
DELETE /products/1 -> delete product 1
but you have to know which parameters you need to send to any request. I hope I was clear...
Every HTTP response has metadata in HTTP headers. One of those HTTP headers is ContentType. The content type identifies a media type which is the contract that the response payload must conform to. The specifications for media types can be found here http://www.iana.org/assignments/media-types/media-types.xhtml
One of the major differences between SOAP and HTTP (as an application protocol) is that SOAP defines the contract at design time, whereas with HTTP the contract is specified in the response message so it can change over time. Therefore it is important for the client to read the content type on each response to know how to process the response.
There is WADL (http://en.wikipedia.org/wiki/Web_Application_Description_Language) although it is not so much used as WSDL for SOAP. REST services written in Java EE automatically generate it as .../application.wadl, PHP suppor is pretty poor as far as I know.
As the others mentioned a web service definition is not necessary for RESTful services, however if you want to create something similar for your API the industry standard is Swagger/OpenAPI, though GraphQL schemas are also becoming a defacto standard too.
There are also a few other options you can also explore (see wikipedia).
Here is a list of the most common options:
swagger.json or openapi.json files in the OpenAPI Spec
GraphQL Schemas with full spec here
Postman Collections which can be published online.
RAML
RSDL

Google Realtime API - How to view existing collaboration model?

How do I view existing realtime collaboration data model? I call getRoot method:
var collaborative_model = rtpg.realtimeDoc.getModel().getRoot()
When I vew collaborative_model object in debug, I see cryptic properties only. Not sure if or how my model is saved.
Can I do some kind of variable dump of the model?
You can use https://gist.github.com/cowsrule/6348393 as a mostly plug-and-play dumper for the realtime API collaborative objects. As this relies on internals of the realtime API it will need to be updated (read: break) the next time they update the API.
To use, include on your webpage and set window.remoteDoc to be your realtime document.
To call, pass in the ID of the CollaborativeObject you are interested in inspecting.
The root is just a CollaborativeMap, so you can use the standard map methods to explore its values.
The relevant methods there for digging into the model are keys() and values().
A lot of these data model classes have obfuscated methods that are a part of the internal implementation. The best way to see what methods are publicly available is to look at the API reference.

wso2 API Manager and BAM - How to control API invocation?

How can I retrieve the number of API invocations? I know the data has to be somewhere because wso2 BAM shows piecharts with similar data...
I would like to get that number in a mediation sequencel; is that possible? Might this might be achieved via a DB-lookup?
The way how API Usage Monitoring in WSO2 API Manager works is, there is an API handler (org.wso2.carbon.apimgt.usage.publisher.APIUsageHandler) that gets invoked for each request and response passing through the API gateway. In this handler all pertinent information with regard to API usage is published to the WSO2 BAM server. The WSO2 BAM server persists this data in Cassandra database that is shipped with it. Then there is a BAM Toolbox that has been packaged with required analytic scripts written using Apache Hive that can be installed on the BAM server. These scripts would summarize the data periodically and persist the summarized data to an sql database. So the graphs and charts shown in the API Publisher web application are created using the summarized data from the sql database.
Now, if what you require is extractable from these summarized sql tables then i suppose the process is very straight forward. You could use the DBLookup mediator for this. But if some dimension of the data which you need has been lost due to the summarizing, then you will have a little more work to do.
You have two options.
The easiest approach which involves no coding at all would be to write a custom Hive script that suits your requirement and summarize data to a sql table. Then, like before use a DBLookup mediator to read the data. You can look at the existing Hive scripts that are shipped with the product to get an idea of how it is written.
If you dont want BAM in the picture, you still can do it with minimal coding as follows. The implementation class which performs the publishing is org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher. This class implements the interface org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataPublisher. The interface has three instace methods as follows.
public void init()
public void publishEvent(RequestPublisherDTO requestPublisherDTO)
public void publishEvent(ResponsePublisherDTO responsePublisherDTO)
The init() method runs just once during server startup. Here is where you can add all your logic which is needed to bootstrap the class.
The publishEvent(RequestPublisherDTO) is where you publish request events and publishEvent(ResponsePublisherDTO) is where you publish response events. The DTO objects are encapsulated representations of the request and response data respectively.
What you will have to do is write a new implementation for this interface and configure it as the value for DataPublisherImpl property in api-manager.xml. To make things easier you can simply extends the exsiting org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher, write your necessary logic to persist usage data to an sql database within the init(), publishEvent(RequestPublisherDTO) and publishEvent(ResponsePublisherDTO) and at the end of each method just call its respective super class method.
E.g. the overriding init() will call super().init(). This way you are only adding the neccessary code for your requirement, and leaving the BAM stat collection requirement to the super class.

Customizing json rendering for sling's userManager

I am trying to build my application's admin UI using sling's userManager REST interface, but I would like to customize the json rendering. For example, I would like the response of "Get group" to include the members only if the requestor is a member.
I started by adding libs/sling/group/json.esp but I don't understand how I can get hold of the default response and customize it. Even if I had to query and form the json from scratch, where can I find information about APIs available to get this data from JCR/Sling?
I found that I could use ResourceTraversor to dump the resource object in json form but using new Packages.org.apache.sling.servlets.get.impl.helpers.ResourceTraversor(-1, 10000, resource, true) in the esp throws up an error
There are a few things to note here.
First, you should avoid putting your code under the libs directory. Your app code should live under the apps directory. When attempting to resolve a servlet for a URI, Sling will check apps before it checks libs so if you need to completely override functionality delivered with Sling, you would place your code in apps.
Second, what is (probably, depending on how you have things setup) happening when you request http://localhost:8080/system/userManager/group/administrators.tidy.1.json is the request is being handled by Sling's default GET servlet, because it finds no other script or servlet which is applicable. For research purposes it might be worth looking at the code for the default get servlet, org.apache.sling.servlets.get.impl.DefaultGetServlet, to see what it's using to render JSON. If you need to handle the rendering of a user group in a manner different than what the default GET servlet is doing, then you would need to create a servlet which is listening for requests for resources of type sling/group. It would probably be ideal to create a servlet for this purpose and register it with OSGI. http://sling.apache.org/site/servlets.html provides the various properties you would need to set to ensure the servlet resolver finds your servlet. Your servlet then would handle the request and as such would have direct and easy access to the requested resource.
Third, the particular need you specified is that you do not want the group members to render unless the requesting user is a member of the group requested. This is more of an access control issue than a rendering issue. Sling and Jackrabbit, out of the box, make as few assumptions as possible concerning how you might want your application to be setup. That being the case, you need to establish the access controls that are applicable for your particular use case. The wiki post on Access Control in the Jackrabbit wiki ( http://wiki.apache.org/jackrabbit/AccessControl ) goes into this to an extent.
Using directions from Paul Michelotti's answer, I researched further and found a suitable solution to my problem.
Sling accepts request filters (javax.servlet.Filter) through SCR annotations like the one below
#SlingFilter(scope = SlingFilterScope.REQUEST, order = Integer.MIN_VALUE)
Every request is passed down to the filter before it is processed by the servlet. Using the resourceType, I was able to distinguish requests to group.1.json and group/mygroup.1.json. Since the filter also has access to the current user, I was able to decide to deny the request if it did not abide by my security model and return a 404 status code.
Please refer to this page for details on filters. You can also check out the sample project urlfilter for directions on usage.