Very short version
How do I include an ADF Variable inside a JSON POST request, in a Web Activity within ADF?
I feel like this should be a very simple string concatenation, but i can't get it to work
Detail
We have a requirement to run a query / SProc from within ADF, which will return a string containing an error message. That string is to then be passed via the Web Activity in ADF to a Logic App, in order to fire off an email, containing the error.
The setup of the logic app is copied from here:
https://www.mssqltips.com/sqlservertip/5718/azure-data-factory-pipeline-email-notification--part-1/
and then here (part 2)
https://www.mssqltips.com/sqlservertip/5962/send-notifications-from-an-azure-data-factory-pipeline--part-2/
In ADF, I used the Lookup activity, to run a query, which brings back the error (appears to work, the preview returns the correct string)
Then I use the Set Variable activity, to take the output of the lookup and store it in a variable.
Last Step is to fire off the POST using the Web Activity.
With this code (tweaked slightly to remove personal details) in my Web Activity, everything works fine and I receive an email
{
"DataFactoryName": "#{pipeline().DataFactory}",
"PipelineName": "#{pipeline().Pipeline}",
"Subject": "Pipeline finished!",
"ErrorMessage": "Everything is okey-dokey!",
"EmailTo": "me#myEmail.com"
}
But any attempt to put the contents of the Variable into the Subject part has failed.
This (for example) sends me an email with the subject literally being #variables('EmailSubject')
{
"DataFactoryName": "#{pipeline().DataFactory}",
"PipelineName": "#{pipeline().Pipeline}",
"Subject": "#variables('EmailSubject')",
"ErrorMessage": "Everything is okey-dokey!",
"EmailTo": "me#myEmail.com"
}
But I've also attempted various other solutions that result in errors or the email subject just containing the literal thing that I put in there (e.g. + #variables('EmailSubject') +).
I also tried storing the entire JSON in the Variable, and then having the Web activity use only the variable, that returned no errors, but also did not send an email.
This attempt:
{
"DataFactoryName": "#{pipeline().DataFactory}",
"PipelineName": "#{pipeline().Pipeline}",
"Subject": "#{variables('EmailSubject')}",
"ErrorMessage": "Everything is okey-dokey!",
"EmailTo": "me#myEmail.com"
}
Resulted in this input into the web activity - which actually includes the text of the error, which is a bonus ... (text = Job Duration Warning):
{
"url": "https://azureLogicAppsSiteHere",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": "{\n \"DataFactoryName\": \"DFNAMEHERE\",\n \"PipelineName\": \"pipeline1\",\n \"Subject\": \"{\"firstRow\":{\"\":\"Job Duration Warning\"},\"effectiveIntegrationRuntime\":\"DefaultIntegrationRuntime (West Europe)\",\"billingReference\":{\"activityType\":\"PipelineActivity\",\"billableDuration\":[{\"meterType\":\"AzureIR\",\"duration\":0.016666666666666666,\"unit\":\"DIUHours\"}]},\"durationInQueue\":{\"integrationRuntimeQueue\":0}}\",\n \"ErrorMessage\": \"Everything is okey-dokey!\",\n \"EmailTo\": \"me#myEmail.com\"\n}\t"
}
But then resulted in this error:
{
"errorCode": "2108",
"message": "{\"error\":{\"code\":\"InvalidRequestContent\",\"message\":\"The request content is not valid and could not be deserialized: 'After parsing a value an unexpected character was encountered: f. Path 'Subject', line 4, position 17.'.\"}}",
"failureType": "UserError",
"target": "Web1",
"details": []
}
[Edit] The PREVIEW from the Lookup Activity is the text: Job Duration Warning BUT when I debug the pipeline, it lets me see the actual Output, which is this:
{
"count": 1,
"value": [
{
"": "Job Duration Warning"
}
],
"effectiveIntegrationRuntime": "DefaultIntegrationRuntime (West Europe)",
"billingReference": {
"activityType": "PipelineActivity",
"billableDuration": [
{
"meterType": "AzureIR",
"duration": 0.016666666666666666,
"unit": "DIUHours"
}
]
},
"durationInQueue": {
"integrationRuntimeQueue": 0
}
}
So it appears that the problem is that the Lookup Output isn't what I thought it was, so the variable can't be used in the Web Activity, as it contains unsupported characters or something along those lines.
I just tested this and it worked ok:
Create a String Parameter with the value Job Duration Warning
Set the Variable value to be #pipeline().parameters.ParamSubject
Include the variable in the web activity with an # in front of it
I then receive my expected email with the right subject. I just don't know how to get the string output of my query, into a variable / parameter, so that i can use it in the web activity.
I don't know how well this applies to other people's issues, but I found a solution that has worked for me.
In the SELECT query within the Lookup Activity - name the output (in my case, I called that column 'Subject'- i.e. SELECT xyz AS Subject
In the Lookup Activity, turn on the setting 'First Row Only'
In the Set Variable Activity, use the code: #activity('Lookup1').output.firstRow.subject
(where 'Lookup1' is the name of your Lookup Activity and Subject is the name of the column you are outputting)
In the Web Activity, reference the variable as follows:
{
"DataFactoryName": "#{pipeline().DataFactory}",
"PipelineName": "#{pipeline().Pipeline}",
"Subject": "#{variables('EmailSubject')}",
"ErrorMessage": "Everything is okey-dokey!",
"EmailTo": "me#myEmail.com"
}
I am posting the results/logs of a CI/CD system to Microsoft Teams. While handling some failed builds with longer results, I stumbled upon the following error returned by the webhook URL https://outlook.office.com/webhook/bb6bfee7-1820-49fd-b9f9-f28f7cc679ff#<uuid1>/IncomingWebhook/<id>/<uuid2>:
Webhook message delivery failed with error: Microsoft Teams endpoint returned HTTP error 413 with ContextId tcid=3626521845697697778,server=DB3PEPF0000009A,cv=BmkbJ1NdTkv1EDoqr7n/rg.0..
As I observe, this is caused by too long payload posted to the Teams webhook URL.
The initial complex message (sections, titles, subtitles, formatted links, <pre> formatted text, etc.) was failing when the JSON payload was a above 18000 characters.
Testing a bit with the payload I observed that the more formatting I remove from the raw JSON payload, the longer can the Teams message be. The longest message I could post had (according cu cURL): Content-Length: 20711. The JSON payload for this message was:
{"themeColor":"ED4B35","text":"a....a"}
whitespaces in the JSON format seem not to count (i.e. adding spaces will not decrease the maximum message length that I can sent to the Teams webhook).
For reference, the initial message was looking similar to this:
{
"themeColor": "ED4B35",
"summary": "iris-shared-libs - shared-library-updates - failure",
"sections": [
{
"activityTitle": "Job: [iris-shared-libs](https://my.concourse.net/teams/hsm/pipelines/iris-shared-libs) - [shared-library-updates #89](https://my.concourse.sccloudinfra.net/teams/hsm/pipelines/iris-shared-libs/jobs/shared-library-updates/builds/89) (FAILURE)",
"activityImage": "https://via.placeholder.com/200.png/ED4B35/FFFFFF?text=F",
"facts": [
{
"name": "Failed step",
"value": "update-shared-libraries"
}
]
},
{
"text": "Trying a new strategy with gated versioned releases",
"facts": [
{
"name": "Repository",
"value": "[iris-concourse-resources](https://my.git.com/projects/IRIS/repos/iris-concourse-resources)"
},
{
"name": "Commit",
"value": "[2272145ddf9285c9933df398d63cbe680a62f2b7](https://my.git.com/projects/IRIS/repos/iris-concourse-resources/commits/2272145ddf9285c9933df398d63cbe680a62f2b7)"
},
{
"name": "Author",
"value": "me#company.com"
}
]
},
{
"activityTitle": "Job failed step logs part 1",
"text": "<pre>...very long log text goes here ...</pre>"
}
]
}
What is the actual maximum lengths of the Microsoft Teams connector webhook posted message?
The official page does not mention it. In the Feedback section at the bottom there is still an open question regarding "Messages size limits?" with the feedback: "We are currently investigating this."
From the tests I made so far, some limits observed (if this is independent of the server) are roughly, based on the JSON message payload (structure and formatting) between 18000 and 40000 (with length below 18000 never breaking and above 40000 always breaking).
Use case 18000: one long text for a section
Use case 40000: 600 facts with very short name and empty string as value
And removing a fragment of the JSON payload and adding an equal number of characters in another JSON value will not give you the same maximum.
I have observed a soft limit (message truncated, but no error) as well on the maximum number of sections: 10. The sections starting with the 11th are discarded.
I'm requesting a list of possible stock ticker symbols from the Yahoo Stock Lookup API, I used the CORS Anywhere service to avoid problems. Unfortunately the original json response from the Yahoo API gets formatted as 'text' in the CORS anywhere 'error' property.
I used this previously asked question as a reference on how to access nested properties.
this is what the json reponse looks like:
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 200,
"statusText": "OK",
"url": "https://cors-anywhere.herokuapp.com/http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=Amd®ion=1&lang=en&callback=YAHOO.Finance.SymbolSuggest.ssCallback",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure during parsing for https://cors-anywhere.herokuapp.com/http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=Amd®ion=1&lang=en&callback=YAHOO.Finance.SymbolSuggest.ssCallback",
"error": {
"error": {
"line": 9848,
"column": 56,
"sourceURL": "capacitor://localhost/vendor-es2015.js"
},
"text": "YAHOO.Finance.SymbolSuggest.ssCallback({\"ResultSet\":{\"Query\":\"Amd\",\"Result\":[{\"symbol\":\"AMD\",\"name\":\"Advanced Micro Devices, Inc.\",\"exch\":\"NMS\",\"type\":\"S\",\"exchDisp\":\"NASDAQ\",\"typeDisp\":\"Equity\"},{\"symbol\":\"DOX\",\"name\":\"Amdocs Limited\",\"exch\":\"NMS\",\"type\":\"S\",\"exchDisp\":\"NASDAQ\",\"typeDisp\":\"Equity\"},{\"symbol\":\"AMDVX\",\"name\":\"American Century Mid Cap Value Fund R6 Class\",\"exch\":\"NAS\",\"type\":\"M\",\"exchDisp\":\"NASDAQ\",\"typeDisp\":\"Fund\"},{\"symbol\":\"AMDWX\",\"name\":\"Amana Mutual Funds Trust Developing World Fund Investor\",\"exch\":\"NAS\",\"type\":\"M\",\"exchDisp\":\"NASDAQ\",\"typeDisp\":\"Fund\"},{\"symbol\":\"AMDAX\",\"name\":\"AMIDEX35 Israel Fund Class A\",\"exch\":\"NAS\",\"type\":\"M\",\"exchDisp\":\"NASDAQ\",\"typeDisp\":\"Fund\"},{\"symbol\":\"AMDEX\",\"name\":\"AMIDEX35 Israel Mutual Fund\",\"exch\":\"NAS\",\"type\":\"M\",\"exchDisp\":\"NASDAQ\",\"typeDisp\":\"Fund\"},{\"symbol\":\"AMDCX\",\"name\":\"AMIDEX35 Israel Fund Class C\",\"exch\":\"NAS\",\"type\":\"M\",\"exchDisp\":\"NASDAQ\",\"typeDisp\":\"Fund\"},{\"symbol\":\"AMDRX\",\"name\":\"American Beacon Mid-Cap Value Fund R6 Class\",\"exch\":\"NAS\",\"type\":\"M\",\"exchDisp\":\"NASDAQ\",\"typeDisp\":\"Fund\"},{\"symbol\":\"AMDLY\",\"name\":\"Amada Holdings Co., Ltd.\",\"exch\":\"PNK\",\"type\":\"S\",\"exchDisp\":\"OTC Markets\",\"typeDisp\":\"Equity\"}]}});"
}
}
This is what I tried:
return this.yahooResult.subscribe(data => {return data['error']['text']['ResultSet']['Result']['symbol']});
I'm trying to access "symbol" : "AMD" from the Yahoo API response that is nested in the "text" property of the CORS repsonse.
I don't get much information from the error:
⚡️ [error] - ERROR
You don't have json there, you have a javascript snippet:
YAHOO.Finance.SymbolSuggest.ssCallback()
With some escaped text passed into it.
It's not a case of parsing this, its a case of fixing the error.
I think you are using the wrong API call. It has a callback parameter in it which is wrapping the reply in a function and breaking cors-anywhere's ability to parse the response.
The url you should be using is:
http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=Amd®ion=1&lang=en
Not:
http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=Amd®ion=1&lang=en&callback=YAHOO.Finance.SymbolSuggest.ssCallback
Then just plain JSON gets returned and cors-anywhere should be able to parse it.
I have read many RESTful API design pattern resources.
But I'm not confident for deciding API.
It seems there does not not exist a standard JSON response format.
I need advice for my Json error response as below.
401
jwt token related fail
{
code:1,
message: "no access token"
}
{
code:2,
message: "invalid access token"
}
{
code:3,
message: "expired access token"
}
400
client's insufficient input parameter
{
code:20,
message: "input paramter 'search' is missing"
}
client's invalid value request
{
code:21,
message: "invalid serial no"
}
client's invalid request format
{
code:22,
message: "input parameter indate is invalid date format"
}
500
another mesh-up server's problem
{
code:30,
message: "no reply from external server API"
}
program logic error (ex. exception)
{
code:31,
message: "internal server error"
}
For 500 cases, I think client also needs more information.
And another concern is "Is error code needed?"
You could use Problem Details for HTTP APIs.
It's a nice format that can be extended easily to provide the client a good way to react on each error/problem appropriately.
https://www.rfc-editor.org/rfc/rfc7807
Here is an example taken from the RFC:
{
"type": "https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"detail": "Your current balance is 30, but that costs 50.",
"instance": "/account/12345/msgs/abc",
"balance": 30,
"accounts": ["/account/12345", "/account/67890"]
}
Do standards or best practices exist for structuring JSON responses from an API? Obviously, every application's data is different, so that much I'm not concerned with, but rather the "response boilerplate", if you will. An example of what I mean:
Successful request:
{
"success": true,
"payload": {
/* Application-specific data would go here. */
}
}
Failed request:
{
"success": false,
"payload": {
/* Application-specific data would go here. */
},
"error": {
"code": 123,
"message": "An error occurred!"
}
}
Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged:
JSON API - JSON API covers creating and updating resources as well, not just responses.
JSend - Simple and probably what you are already doing.
OData JSON Protocol - Very complicated.
HAL - Like OData but aiming to be HATEOAS like.
There are also JSON API description formats:
Swagger
JSON Schema (used by swagger but you could use it stand alone)
WADL in JSON
RAML
HAL because HATEOAS in theory is self describing.
Google JSON guide
Success response return data
{
"data": {
"id": 1001,
"name": "Wing"
}
}
Error response return error
{
"error": {
"code": 404,
"message": "ID not found"
}
}
and if your client is JS, you can use if ("error" in response) {} to check if there is an error.
I guess a defacto standard has not really emerged (and may never).
But regardless, here is my take:
Successful request:
{
"status": "success",
"data": {
/* Application-specific data would go here. */
},
"message": null /* Or optional success message */
}
Failed request:
{
"status": "error",
"data": null, /* or optional error payload */
"message": "Error xyz has occurred"
}
Advantage: Same top-level elements in both success and error cases
Disadvantage: No error code, but if you want, you can either change the status to be a (success or failure) code, -or- you can add another top-level item named "code".
Assuming you question is about REST webservices design and more precisely concerning success/error.
I think there are 3 different types of design.
Use only HTTP Status code to indicate if there was an error and try to limit yourself to the standard ones (usually it should suffice).
Pros: It is a standard independent of your api.
Cons: Less information on what really happened.
Use HTTP Status + json body (even if it is an error). Define a uniform structure for errors (ex: code, message, reason, type, etc) and use it for errors, if it is a success then just return the expected json response.
Pros: Still standard as you use the existing HTTP status codes and you return a json describing the error (you provide more information on what happened).
Cons: The output json will vary depending if it is a error or success.
Forget the http status (ex: always status 200), always use json and add at the root of the response a boolean responseValid and a error object (code,message,etc) that will be populated if it is an error otherwise the other fields (success) are populated.
Pros: The client deals only with the body of the response that is a json string and ignores the status(?).
Cons: The less standard.
It's up to you to choose :)
Depending on the API I would choose 2 or 3 (I prefer 2 for json rest apis).
Another thing I have experienced in designing REST Api is the importance of documentation for each resource (url): the parameters, the body, the response, the headers etc + examples.
I would also recommend you to use jersey (jax-rs implementation) + genson (java/json databinding library).
You only have to drop genson + jersey in your classpath and json is automatically supported.
EDIT:
Solution 2 is the hardest to implement but the advantage is that you can nicely handle exceptions and not only business errors, initial effort is more important but you win on the long term.
Solution 3 is the easy to implement on both, server side and client but it's not so nice as you will have to encapsulate the objects you want to return in a response object containing also the responseValid + error.
The RFC 7807: Problem Details for HTTP APIs is at the moment the closest thing we have to an official standard.
Following is the json format instagram is using
{
"meta": {
"error_type": "OAuthException",
"code": 400,
"error_message": "..."
}
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}
I will not be as arrogant to claim that this is a standard so I will use the "I prefer" form.
I prefer terse response (when requesting a list of /articles I want a JSON array of articles).
In my designs I use HTTP for status report, a 200 returns just the payload.
400 returns a message of what was wrong with request:
{"message" : "Missing parameter: 'param'"}
Return 404 if the model/controler/URI doesn't exist
If there was error with processing on my side, I return 501 with a message:
{"message" : "Could not connect to data store."}
From what I've seen quite a few REST-ish frameworks tend to be along these lines.
Rationale:
JSON is supposed to be a payload format, it's not a session protocol. The whole idea of verbose session-ish payloads comes from the XML/SOAP world and various misguided choices that created those bloated designs. After we realized all of it was a massive headache, the whole point of REST/JSON was to KISS it, and adhere to HTTP. I don't think that there is anything remotely standard in either JSend and especially not with the more verbose among them. XHR will react to HTTP response, if you use jQuery for your AJAX (like most do) you can use try/catch and done()/fail() callbacks to capture errors. I can't see how encapsulating status reports in JSON is any more useful than that.
For what it's worth I do this differently. A successful call just has the JSON objects. I don't need a higher level JSON object that contains a success field indicating true and a payload field that has the JSON object. I just return the appropriate JSON object with a 200 or whatever is appropriate in the 200 range for the HTTP status in the header.
However, if there is an error (something in the 400 family) I return a well-formed JSON error object. For example, if the client is POSTing a User with an email address and phone number and one of these is malformed (i.e. I cannot insert it into my underlying database) I will return something like this:
{
"description" : "Validation Failed"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Invalid phone number."
} ],
}
Important bits here are that the "field" property must match the JSON field exactly that could not be validated. This allows clients to know exactly what went wrong with their request. Also, "message" is in the locale of the request. If both the "emailAddress" and "phoneNumber" were invalid then the "errors" array would contain entries for both. A 409 (Conflict) JSON response body might look like this:
{
"description" : "Already Exists"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Phone number already exists for another user."
} ],
}
With the HTTP status code and this JSON the client has all they need to respond to errors in a deterministic way and it does not create a new error standard that tries to complete replace HTTP status codes. Note, these only happen for the range of 400 errors. For anything in the 200 range I can just return whatever is appropriate. For me it is often a HAL-like JSON object but that doesn't really matter here.
The one thing I thought about adding was a numeric error code either in the the "errors" array entries or the root of the JSON object itself. But so far we haven't needed it.
Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.
As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?
Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:
https://github.com/adnan-kamili/rest-api-response-format
Swagger file:
https://github.com/adnan-kamili/swagger-sample-template
The point of JSON is that it is completely dynamic and flexible. Bend it to whatever whim you would like, because it's just a set of serialized JavaScript objects and arrays, rooted in a single node.
What the type of the rootnode is is up to you, what it contains is up to you, whether you send metadata along with the response is up to you, whether you set the mime-type to application/json or leave it as text/plain is up to you (as long as you know how to handle the edge cases).
Build a lightweight schema that you like.
Personally, I've found that analytics-tracking and mp3/ogg serving and image-gallery serving and text-messaging and network-packets for online gaming, and blog-posts and blog-comments all have very different requirements in terms of what is sent and what is received and how they should be consumed.
So the last thing I'd want, when doing all of that, is to try to make each one conform to the same boilerplate standard, which is based on XML2.0 or somesuch.
That said, there's a lot to be said for using schemas which make sense to you and are well thought out.
Just read some API responses, note what you like, criticize what you don't, write those criticisms down and understand why they rub you the wrong way, and then think about how to apply what you learned to what you need.
JSON-RPC 2.0 defines a standard request and response format, and is a breath of fresh air after working with REST APIs.
The basic framework suggested looks fine, but the error object as defined is too limited. One often cannot use a single value to express the problem, and instead a chain of problems and causes is needed.
I did a little research and found that the most common format for returning error (exceptions) is a structure of this form:
{
"success": false,
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
This is the format proposed by the OASIS data standard OASIS OData and seems to be the most standard option out there, however there does not seem to be high adoption rates of any standard at this point. This format is consistent with the JSON-RPC specification.
You can find the complete open source library that implements this at: Mendocino JSON Utilities. This library supports the JSON Objects as well as the exceptions.
The details are discussed in my blog post on Error Handling in JSON REST API
For those coming later, in addition to the accepted answer that includes HAL, JSend, and JSON API, I would add a few other specifications worth looking into:
JSON-LD, which is a W3C Recommendation and specifies how to build interoperable Web Services in JSON
Ion Hypermedia Type for REST, which claims itself as a "a simple and intuitive JSON-based hypermedia type for REST"
There is no lawbreaking or outlaw standard other than common sense. If we abstract this like two people talking, the standard is the best way they can accurately understand each other in minimum words in minimum time. In our case, 'minimum words' is optimizing bandwidth for transport efficiency and 'accurately understand' is the structure for parser efficiency; which ultimately ends up with the less the data, and the common the structure; so that it can go through a pin hole and can be parsed through a common scope (at least initially).
Almost in every cases suggested, I see separate responses for 'Success' and 'Error' scenario, which is kind of ambiguity to me. If responses are different in these two cases, then why do we really need to put a 'Success' flag there? Is it not obvious that the absence of 'Error' is a 'Success'? Is it possible to have a response where 'Success' is TRUE with an 'Error' set? Or the way, 'Success' is FALSE with no 'Error' set? Just one flag is not enough? I would prefer to have the 'Error' flag only, because I believe there will be less 'Error' than 'Success'.
Also, should we really make the 'Error' a flag? What about if I want to respond with multiple validation errors? So, I find it more efficient to have an 'Error' node with each error as child to that node; where an empty (counts to zero) 'Error' node would denote a 'Success'.
I used to follow this standard, was pretty good, easy, and clean on the client layer.
Normally, the HTTP status 200, so that's a standard check which I use at the top. and I normally use the following JSON
I also use a template for the API's
dynamic response;
try {
// query and what not.
response.payload = new {
data = new {
pagination = new Pagination(),
customer = new Customer(),
notifications = 5
}
}
// again something here if we get here success has to be true
// I follow an exit first strategy, instead of building a pyramid
// of doom.
response.success = true;
}
catch(Exception exception){
response.success = false;
response.message = exception.GetStackTrace();
_logger.Fatal(exception, this.GetFacadeName())
}
return response;
{
"success": boolean,
"message": "some message",
"payload": {
"data" : []
"message": ""
... // put whatever you want to here.
}
}
on the client layer I would use the following:
if(response.code != 200) {
// woops something went wrong.
return;
}
if(!response.success){
console.debug ( response.message );
return;
}
// if we are here then success has to be true.
if(response.payload) {
....
}
notice how I break early avoiding the pyramid of doom.
I use this structure for REST APIs:
{
"success": false,
"response": {
"data": [],
"pagination": {}
},
"errors": [
{
"code": 500,
"message": "server 500 Error"
}
]
}
A bit late but here is my take on HTTP error responses, I send the code, (via status), the generic message, and details (if I want to provide details for a specific endpoint, some are self explanatory so no need for details but it can be custom message or even a full stack trace depending on use case). For success it's a similar format, code, message and any data in the data property.
ExpressJS response examples:
// Error
res
.status(422)
.json({
error: {
message: 'missing parameters',
details: `missing ${missingParam}`,
}
});
// or
res
.status(422)
.json({
error: {
message: 'missing parameters',
details: 'expected: {prop1, prop2, prop3',
}
});
// Success
res
.status(200)
.json({
message: 'password updated',
data: {member: { username }}, // [] ...
});
Best Response for web apis that can easily understand by mobile developers.
This is for "Success" Response
{
"code":"1",
"msg":"Successfull Transaction",
"value":"",
"data":{
"EmployeeName":"Admin",
"EmployeeID":1
}
}
This is for "Error" Response
{
"code": "4",
"msg": "Invalid Username and Password",
"value": "",
"data": {}
}