APEX Rest API - Swagger - salesforce

I am a bit new to the whole APEX service plugins but I was wondering if Salesforce has native support for Swagger, or any similar REST description language, for the REST api's that I create in the APEX service platform?
For example:
#RestResource(urlMapping='/v1/users/*')
global with sharing class UserRestService {
...
#HttpGet
global static List<Member__c> doGet(....)
{
...
}
}
I would like the ability to return the swagger json, a WADL document, or something for this REST service (and all other REST services I have in there). Does anyone know of a way I can do this?
Thanks in advance!

There is no built in support at this time. I was interested in seeing what could be done via currently available public APIs. The first thing I ran into is the grammar does not seem to like parameters to HttpGet methods. That right there will make it challenging since the only way to get input parameters appears to be via the Request entity which means you would have to parse the actual code. In other words, there does not appear to be declarative input binding.
Further, in looking at the tooling API which let's me get some amount of "reflective" information about the class, there is not always sufficient information to render a response payload (in your case, it just shows LIST but not what's in the list)
Again, it looks like one would have to rely on a parser (there is at least one Antl grammar floating around).
(this is getting some internal attention but I can't say any more at this time)

Related

Azure AD B2C Custom Policy Localized REST API Conflict Response

This is sort of an extension of this question here. I have a policy that calls a REST API. The API returns an error message and this message needs to be localized.
One way is to of course get the API to return a localized message, but is there a way for the CustomPolicy itself to localize the error code? According to the CustomPolicy Docs, a REST API can send an error code along with the Conflict error code. Our thinking was to use this error code as a key and select a localized message (from the messageValue enum mentioned in the answer in the link).
However, we can't seem to capture/handle the error data returned by the API. The Policy seems to handle error codes by itself and we would like to know if it is possible to inject localized exception/error messages from the policy itself.
Thanks in advance!
Edit: A little more information about the setup. We have a TechnicalProfile that has a DisplayWidget and a ValidationTechnicalProfile. The DisplayWidget is used for entering & verifying the user's phone/email and the ValidationTechnicalProfile makes the final call to the RestAPI with all the user's information to register him/her. This RestAPI call output is what we want to localize.
The suggestion in the linked SO question, from what I understand, is that we integrate another DisplayClaim (that references an enum) in the DisplayWidget, and depending on the ErrorCode returned by the call, change it to display the appropriate code. However, as per my understanding, this would also require editing the API to return only 200 along with a code. This code would indicate the true nature of the result - success or a code for one of the enums to be displayed.
Our aim therefore is to check if there is a way to follow the Policy's flow (disrupt the SignUp/SignIn process) but at the same time localize the API's displayed response.
We managed to find a workaround to this, so I'm posting this here for anyone else who might be interested in this.
Our restriction for localizations was the fact that used Phrase to manage our translations and wanted the CustomPolicy specific translations all in one place. Our CD workflow was as follows:
PolicyCommit -> Build Variable Replacement through PS -> Release Variable Replacement and localized strings replacement through PS & Policy Uploads
Barring the policy from localizing the APIs response, we had the following options to achieve this:
Sending the language to the API and having the API return the appropriate error message
in the appropriate language. We were reluctant to follow this because of a multitude of reasons, but mostly because we would also have to handle different regions, etc. in the API - something the policy does by itself.
We actually had only one API that we called, and also only two error messages that were used. Hence we created an enum with the two error messages that would be localized. We then used a chain of InputClaimsTransformations that did the following:
Repeat Steps 1 through 3 for all the errors
1. CreateStringClaim (Create ClaimTypes for each of the error codes, holding the index of the error code in the enum)
2. GetMappedValueFromLocalizedCollection (Make the localized enum choose and hold the value of the required error code)
3. AddItemToStringCollection (Add the localized error from the enum to a StringCollection)
4. GenerateJson (Add the error codes StringCollection to the JSON payload to be sent to the API)
This way, the policy performed the localization for all the errors and we sent them along with the request to the API. The API, when an error occurred, picked one of the error messages from the policy and sent it back. This method was for us, because of our CD structure and Phrase integration, much easier than actually having the translations in a file hosted on the cloud to be accessed by the API.
Hope this helps someone; I can also add code in case someone needs it :)

Best practices for model validation using a REST API and a javascript front-end such as Angular

I'm transitioning towards more responsive front-end web apps and I have a question about model validation. Here's the set-up: the server has a standard REST API for inserting, updating, retrieving, etc. This could be written in Node or Java Spring, it doesn't matter. The front-end is written with something like Angular (or similar).
What I need is to figure out where to put the validation code. Here's the requirements:
All validation code should be written in one place only. Not both client and server. this implies that it should reside on the server, inside the REST API when persisting.
The front-end should be capable of understanding validation errors from the server and associating them to the particular field that caused the error. So if the field "username" is mandatory, the client can place an error next to that field saying "Username is mandatory".
It should be possible to validate correct variable types. So if we were expecting a number or a date and got a string instead, the error would be something like "'Yo' is not a correct date."
The error messages should be localized to the user's language.
Can anyone help me out? I need something simple and robust.
Thanks
When validating your input and it fails you can return a response in appropriate format (guessing you use JSON) to contain the error messages along with a proper HTTP error code.
Just working on a project with a Symfony backend, using FOSRestBundle to provide proper REST API. Using the form component of Symfony whenever there's a problem with the input a well structured JSON response is generated with error messages mapped to the fields or the top level if for example there's unexpected input.
After much research I found a solution using the Meteor.js platform. Since it's a pure javascript solution running on both the server and the client, you can define scripts once and have them run on both the client and the server.
From the official Meteor documentation:
Files outside the client, server and tests subdirectories are loaded on both the client and the server! That's the place for model definitions and other functions.
Wow. Defining models and validation scripts only once is pretty darn cool if you ask me. Also, there's no need to map between JSON and whatever server-side technology. Plus, no ORM mapping to get it in the DB. Nice!
Again, from the docs:
In Meteor, the client and server share the same database API. The same exact application code — like validators and computed properties — can often run in both places. But while code running on the server has direct access to the database, code running on the client does not. This distinction is the basis for Meteor's data security model.
Sounds good to me. Here's the last little gem:
Input validation: Meteor allows your methods and publish functions to take arguments of any JSON type. (In fact, Meteor's wire protocol supports EJSON, an extension of JSON which also supports other common types like dates and binary buffers.) JavaScript's dynamic typing means you don't need to declare precise types of every variable in your app, but it's usually helpful to ensure that the arguments that clients are passing to your methods and publish functions are of the type that you expect.
Anyway, sounds like I've found the a solution to the problem. If anyone else knows of a way to define validation once and have it run on both client and server please post an answer below, I'd love to hear it.
Thanks all.
To be strict, your last gate keeper of validation for any CRUD operations is of course on server-side. I do not know what is your concern that you should handle your validation on one end only(either server or client), but usually doing on both sides is better for both user experience and performance.
Say your username field is a mandatory field. This field can be easily handled in front-end side; before a user click submit and then been sent to the server and then get returned and shows the error code. You can save that round trip with a one liner code in front-end.
Of course, one may argue that from client-side the bad guys may manipulate the data and thus bypassing the front-end validation. That goes to my first point - your final gate keeper in validation should be on your server-side. That's why, data integrity is still the server's job. Make sure whatever that goes into your database is clean, dry and valid.
To answer you question, (biased opinion though) AngularJS is still a pretty awesome framework to let you do front-end validation, as well as providing a good way to do server-side error handling.

Apex only for force.com hosted apps?

Is Apex only permitted on “native” applications that are hosted on force.com?
Or is Apex also available for external applications to hit the “Open APIs” such as REST API and Bulk API?
I think part of my confusion lies in how the term “Rest API” is used in various documents. In other parts of the software world, REST is usually means an HTTP based protocol to exchange data across different domains (and with certain formats, etc ). However, I think Rest API in sales force might SOMETIMES refer to an optional means for native apps to retrieve salesforce data from within force.com. Is that correct?
Not sure I understand your question...
Apex can be used "internally" in:
database triggers,
classes
Visualforce controllers that follow MVC pattern,
logic that parses incoming emails and for example makes Case or Lead records out of them,
asynchronous jobs that can be scheduled to recalculate some important stuff every night
and you can have utility classes for code reuse across these
A "kind of internal" would be to use the "Execute Anonymous" mechanism that lets you fire one-off code snippets against environment. Useful for prototyping of new classes, data fixes etc. You can do it for example in Eclipse IDE or the Developer Console (upper right corner next to your name).
And last but not least - "external" usage.
Apex code can be exposed as webservice and called by PHP, .NET, Java, even JavaScript applications. It's a good choice when:
you want to reuse same piece of logic for example on your own Visualforce page as well as in some mobile application that would be passing couple strings around or a simple JSON object
beats having to reimplement the logic in every new app and maintaining that afterwards
imagine insertion of Account and Contact in one go - your mobile device would have to implement some transaction control and delete the Acc if the Contact failed to load. Messy. And would waste more API calls (insert acc, insert con, ooops, delete acc). With a method exposed as webservice you could accept both parameters into your Apex code, do your magic and well, if it fails - it's all in one transaction so SF will roll it back for you.
There are 2 main methods:
SOAP API primarily uses global methods marked with webservice keyword. Easiest way for other applications to start calling these is to extract from SF and "consume" so-called "enterprise WSDL" file. It's a giant XML file that can be parsed in your .NET app to generate code that will help you write code you're familiar with. These generated classes will construct the XML message for you, send it, process the response (throw your own exceptions if SF has sent an error message) and so on.
Very simple example:
global class MyWebService {
webService static Id makeContact(String lastName, Account a) {
Contact c = new Contact(lastName = 'Weissman', AccountId = a.Id);
insert c;
return c.id;
}
}
REST API allows you to do similar things but you need to use correct HTTP verbs ("PUT" is best for inserts, "PATCH" for updates", "DELETE" and so on).
You can read more about them in the REST API guide: http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#CSHID=apex_rest_methods.htm|StartTopic=Content%2Fapex_rest_methods.htm|SkinName=webhelp

How do you return a Partial response in app engine python endpoints?

I am learning endpoints and saw that other Google APIs have this "fields" query attribute.
Also it appears in the api explorer.
I would like to get a partial response for my api also, but when using the fields selector from the api explorer it is simply ignored by the server.
Do I need to implement something in the server side?
Haven't found anything in the docs.
Any help is welcome.
From what I gather, Google has enabled partial response for their APIs, but has not yet explained how to enable it for custom APIs.
I'm assuming if they do let us know, it might entail annotations, and possibly overriding a method or two.
I've been looking also, to no avail.
I've been looking into this just due to a related question, where I'd like to know how to force the JSON object in the response from my google Endpoint API, to include even the members of the class that are null valued.
I was trying to see if anything would be returned if I used a partial response with a field indicated that was null.. would the response have the property at least, or would it still not even exist as a property.
Anyway, this lead me into the same research, and I do not believe we can enable partial responses in our own APIs yet.
You can return a partial response by defining the parameter in #MyModel.method
#MyModel.method(path='mymodel',
http_method='POST',
name='mymodel.insert',
response_fields=('model_id', 'date_time'))
def mymodel_insert(self, mymodel):
mymodel.put()
return mymodel
Check out this tutorial Endpoints tutorial

Accessing FacesContext in Portal Application

We need to get certain information from PortletRequest in our Portal application. We do that using a utility method inside our Portlet Application. In this Utility method we access FacesContext.getCurrentInstance().getRequest() to get the PortletRequest. We access this Utility method in our DAO layer. We do not have access to request parameter here.
It works sometimes, but at times it gives me NullPointerException. I found a similar thread which explains about this. They have mentioned, if it is part of the same request, then you should get the Context. For me, it is part of the same request, but I'm not getting the context. Can you please help me.
If you are getting a null FaceContext from FacesContext.getCurrentInstance() then no FacesContext has been constructed for this Thread/Request.
Are the failing requests coming through a non-faces entry point? Such as an Event or Resource portlet request? If so there will be no FacesContext created.
Rather than relying on static methods and thread local storage to access data in you DAO you should consider extracting what you need from the PortletRequest, and passing it down your stack. It is bad practice to mix presentation layer artefacts such as the FaceContext or a PortletRequest with your DAO layer.
If your application is deployed in separate WAR/JAR files, it is likely that different classloaders are used. I had a similar problem, when I tried to access the FacesContext inside an hibernate HAR archive on JBOSS5. I came up with a successfull solution using reflection API. Take a look at this.
If you bundle your whole application into one EAR, you might be able to force the use of one classloader for the whole ear, but AFAIK that is application server specific.
Regards

Resources