GithubHelp home page GithubHelp logo

Errors? about json-api HOT 56 CLOSED

steveklabnik avatar steveklabnik commented on May 22, 2024
Errors?

from json-api.

Comments (56)

paddycarver avatar paddycarver commented on May 22, 2024 2

I have very strong opinions on this particular subject, because I flip a table in rage every time I have to interact with an API's errors, because every API sucks at returning useful information. And the number of strings returned above is really, really scaring me. So I will propose the solution I use, which I feel is pretty good, but I'll also share the principles I used to arrive at that solution and why I believe they're important.

Why are we providing information about what went wrong?

The first part of this is the part that gets me angry so often. Most APIs do not consider this question when designing errors, and that makes them a pain to work with.

I humbly submit that errors are returned to instruct the user on how to fix their error. This means that all of and only the user-relevant information should be returned, including the precise reason what the user did was not acceptable.

The reason this is important is because the API is not responsible for the user interface. That is why I'm against APIs passing back an error message that they expect to be displayed to the end user. Most of them do this as the only description of the problem you get, which makes it hard to have, e.g. in form validation, a good user experience. How do you display the error adjacent to the relevant field if there's no way to determine which field produced the error?

If your answer is "parse the string and look for information in that", I want to go cry in the corner now. When error messages are the only description of the error that occurred, you are essentially forcing every client library to just tell their users "Your request is bad and you should feel bad", because it's impossible for them to get more useful information than that.

The reason that you should only expose user-relevant information is because anything else bloats the client libraries for absolutely no reason. I was working on a company's API when I discovered a validation call returned two separate errors based on the way the call was invalid. When asked about it, the company explained that one error was when the invalidity was detected in their own system, the other when the invalidity was detected in the third party system they called in the background. They were unable to explain to me why I should care where the call was invalidated, because that made absolutely no difference to the end user. If you're returning that information for debugging purposes, it belongs in logs, not in things that client libraries have to deal with.

So here are the principles I came up with:

  1. Every error should prompt one, and only one, action that is necessary to correct the error.
  2. Error details should always be returned in a machine-readable format. Parsing error messages is crazy, brittle, and a code smell.
  3. Each request can have more than one error. Responses should expose as many errors as possible, so that users can fix their request once, not once per each mistake.

Now that my novel/rant/mission-to-civilise is finished, I'll share my proposed solution.

Errors are simply objects in the response body, similar to any other resource. They are returned in an array, with the key of errors (assuming, of course, we adopt #8). Each error object is made up of two pieces of information: a specific error code (not an HTTP error code. These error codes are something like "invalid format", "invalid value", "already in use", "too short", "too long", etc.) and the specific field that raised that error. I'm currently returning that second piece of information with two keys ("field" and "item"; field represents the specific field "post.title" and the item represents the position in the request. E.g., if three posts are created at once, and the error field is "post.title", the error code is "too_long", and the error item is 1, that means the second post's title is too long and needs to be shortened). I think a superior solution would be to combine them in one using RFC 6901 to point to the specific item in the request that was wrong.

So errors would look like this:

{
  "errors": [
    {
      "code": "too_long",
      "field": "/posts/0/title"
    },
    {
      "code": "invalid_format",
      "field": "/posts/1/slug"
    }
  ]
}

This would mean that the first post in the request had a title that was too long, and the application should tell the user to shorten that title, and that the second post has an invalid character in its slug, and the application should tell the user that there's an invalid character. The second example is not perfect; ideally, the response would tell the application which character threw the error (perhaps /posts/1/slug/4, to designate that the 5th character was the problem?) but that level of granularity is hard to obtain while not bloating other errors unnecessarily.

from json-api.

luisobo avatar luisobo commented on May 22, 2024 1

My thoughts on errors

Errors are not always resource-centric

The way rails structure errors works great when an error is referring to a specific attribute of a resource but that's not always the case, like in bad requests, rate-limiting... you name it. The use of base is a workaround that a) does not scale if you want to report as many errors as possible per response and b) conflicts with a real attribute called base

I'd not stick with this specific way of structuring errors.

Error IDs

When consuming an API I always find very useful errors with a unique ID. Especially when all possible errors with their IDs are properly documented.

Most of the time only a subset of all the possible errors are recoverable by the user (i.e. a validation is recoverable but a malformed request is not). Note that this classification is client-specific. The error IDs come in handy to classify client-side which errors are user-recoverable and which are not so, when getting a error, I'd only prompt the user if the given error can be recovered, otherwise raise or fail gracefully.

Developer error message vs UI error message.

Returning two separate error messages will make the learning curve of the API at hand more moderate. Also it encourages the server to return a meaningful error message for the final user, instead of the current approach, where most services will return a message that falls in the middle and leaves no one happy. These messages can be overridden by the client using a client-side mapping between error IDs and the desired new message. But in my personal my experience, most of the time a well thought out message from the server will work for the UI.

Links to the documentation

Also, consider including a link to the documentation where the developer could find more info about the error. This could be in a separate attribute of the document of inside the developer message.

Some random example:

{
  "errors":[{
    "id": 1234,
    "developer_message": "Bro do u even oauth? Check the auth token",
    "user_message": "The provided credentials are invalid.",
    "more_info":"http//developers.example.com/docs/authentication",
    "rel": null
  },{
    "id": 2233,
    "developer_message": "Invalid name. It should match the regex '^\d.*$'",
    "user_message": "must start with a digit",
    "rel": {
      "dog": [1],
      "attribute": "name"
    },
    "more_info":"http//developers.example.com/v1/dog#name"
  }]
}

I'd be surprised to see these two errors together, but you get the idea.

I like the idea of referencing the invalid resource in the original request. I included @hjdivad's format and grouped everything into a rel node.

from json-api.

paddycarver avatar paddycarver commented on May 22, 2024 1

I can get behind @hjdivad's suggestions. I like meta, I'm uncomfortable but accepting of rel, and if someone wants to include a message in meta, who am I to stop them?

In response to @luisobo's excellent points:

Errors are not always resource-centric

I'm actually approaching this from a Go standpoint, not a Ruby one, but I'll address the main point anyways. According to RFC 6901, which is how I'd prefer to specify the object/field that caused the error, an empty string ("") represents the entire document. So how I handle this, personally, is setting the code to something that makes the error obvious (invalid_request_format for bad JSON formatting, act_of_god for internal server errors, etc.) and set the field property to an empty string. I think this addresses your concern that the error be bound to a specific resource?

Error IDs

Agreed. I believe that's the purpose of the proposed code field. You say tomato...

Developer error message vs UI error message.

I've stated my radical opinion on this before, and I'll state it again: I believe it is an anti-pattern to pass a string returned by the API directly to the user. UI error messages do not belong in the API, they belong in the UI. The only error messages that (I think) make sense in an API are developer error messages.

Links to the documentation

I would think this is something that an API could support on its own, using the meta field, without needing to make it part of the spec. I also think that standardising on this is a bad idea, because it is atrociously wasteful in performance-sensitive applications and bandwidth-sensitive applications. The documentation will only be used during development, and all that data is being shipped over the wire for every user in production. That's silly.

I'd also still advocate for using a JSON Pointer to identify the part of the request that caused the error, rather than embedding it back in the response. That seems wasteful, and runs afoul of your original point above because it becomes harder to signify the entire request, instead of a specific part.

from json-api.

wrightling avatar wrightling commented on May 22, 2024

I've been scouring the internet a bit as I work on my first JSON API (using rails-api). Two references I came across return errors in some varation of { error: "message" } or { errors: ["message1", "message2"] }. Is there a more standard way?

Referencing sample app from a rails 3 book sample app ticketee and a Travis Jeffery blog post.

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

I feel like there is some sort of interent-draft for an errors spec, but I can't find it at the moment.

from json-api.

wrightling avatar wrightling commented on May 22, 2024

Here are a few more examples:

Looks like there is nothing if not variety in how folks are returning errors. Personally, I'm not sure I see a point in Google's recommendation to include the code in the response body - seems like duplication.

from json-api.

bcardarella avatar bcardarella commented on May 22, 2024

We've discussed this in the Ember CF quite a bit. The errors object should be a key/value of arrays. So { 'errors': { 'first_name': [] } }

What is not as clear is if full messages should be retured in the array or references to messages that will be determined by the client. The discussion seemed to be in favor of returning message keys that can then be rendered by the client's i18n message processor.

from json-api.

wrightling avatar wrightling commented on May 22, 2024

The format you suggest would be pretty darn easy to support in rails or rails-api as well, as shown in this gist

from json-api.

trek avatar trek commented on May 22, 2024

Please, for all that is good in the world, provide as detailed data as possible.

Working with APIs that return just a string (when I've specifically said "I'll only accept application/json') or only string messages inside JSON {errors: ["good luck figuring out what property is wrong", "hope you like regexps"] }` when the design calls for highlighting where on the page the user erred has got to be on of the most frustrating experiences as UI engineering.

For maximum usefulness, I usually at minimum want something like:

{
  "errors": {
    "firstName": ["cannot be blank", "must be 10+ characters"],
    "lastName": ["cannot contain symbols"]
  }
}

Given the format of what JSON API looks like so far though, I'd expect returned errors to behave exactly like any compound document and include as much about each error object as possible.

from json-api.

bcardarella avatar bcardarella commented on May 22, 2024

@trek would something like this be more to your liking?

{
  "errors": {
    "firstName: [{"key":"blank", "options"{}}, {"key":"tooShort", "options": {"count": 10, "value": 5}}]
  }
}

from json-api.

wycats avatar wycats commented on May 22, 2024

Can we discuss how to handle errors for compound requests? I'm really interested in people's feedback on that topic.

from json-api.

hjdivad avatar hjdivad commented on May 22, 2024

I like @paddyforan's suggestion, although I would add a couple things:

  • It should be possible to specify related documents for cases like name conflicts.
  • It should be possible to specify meta information within errors to specify things like allowable characters or length requirements.
  • It should be possible to specify error messages. Although I agree that it's good to encourage codes on the server and expect clients to produce user-visible messages, I fear this may discourage adoption. If we allow meta information, it's easy enough to have the error messages there.

In the following examples code is required, everything else is optional.

Examples:

// compound request error involving a new resource and an existing resource
// POST /posts
errors: [{
  code: "name_conflict",
  field: "title",
  rels: {
    posts: [1]
  },
  meta: {
    message: "There is already a post with title 'Rails is Omakase'"
  }
}]

// compound request error involving a new resource and an existing resource of a different type
// POST /posts
errors: [{
  code: "insufficient_funds",
  rels: {
    accounts: [1]
  },
  meta: {
    message: "Your account does not have enough credits to create this post."
  }
}]

// metadata that makes the error code more specific
// POST /posts
errors: [{
  code: "insufficient_funds",
  rels: {
    accounts: [1]
  },
  meta: {
    cost: 200,
    balance: 100,
    message: "Your account does not have enough credits to create this post."
  }
}]

// Error not associated with a particular field
// POST /posts
errors: [{
  code: "unknown",
  meta: {
    message: "The server had an unexpected error.  Please try again later."
  }
}]

from json-api.

litch avatar litch commented on May 22, 2024

I'm currently starting on an API using AMS, and encountered this issue. I like the errors attached to the object, I like the problematic attribute to be identifiable, and I want to a message (or messages) about the attribute displayed.

So I'm going to explore an errors "attribute" in my serializer like:

def errors
  if object.errors
    errors = Hash.new([])
    object.errors.each do |k,v|
      errors[k] << v
    end
  end
end

Which yields:

"order" => {
  "errors" => {
    "balance_due" => [
      "Order cannot be closed with balance due: $1.0"
    ]
  },
  "id" => 123477,
  "state" => "open",
  ...etc...

from json-api.

mamund avatar mamund commented on May 22, 2024

i usually just define an error object/block in my API message format:

also consider the following as possible models for reporting errors:

other things to keep in mind:

  • always report two levels of error information protocol-level (4xx and 5xx) and application-level (invalid inputs, data conflicts. etc.).
  • return a body w/ all 4xx & 5xx errors that include the app-level details.
  • for 503 errors consider add the Retry-After header (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.37)

from json-api.

luisobo avatar luisobo commented on May 22, 2024

@paddyforan

Errors are not always resource-centric

I don't have an strong opinion on the format used to point which object/field caused the problem as long as it's easy to express the scenarios described above.

Developer error message vs UI error message.

You mentioned that displaying API errors is an anti-pattern but I failed to understand your reasons, could you please rephrase them?

Personally, I'd consider it an anti-pattern if there is no such thing as a separation between user and dev messages and/or error messages are not properly documented, leaving no opportunity to the developer to check if these error messages are suitable for a UI or not. So yeah, if I have no effing idea about what is coming back from the server as an error I'd never put that in the UI.

Now, the point of including such separation is to force the service to return a good error message (meaningful, proper grammar, punctuation, no error codes in the message, etc). I'd also expect this errors to be properly documented. In this case, I'd not hesitate to take advantage of the error messages coming from the server.

Links to the documentation

I agree with you. This is a nice to have and probably based on necessities that will vary from business to business. (For your business performance is important, for mine it is to make the API easy to use for new developers). It could also be optionally included as part as the developer message as I suggested.

from json-api.

paddycarver avatar paddycarver commented on May 22, 2024

The reason I claim it is an anti-pattern to pass a string from the API directly to the user is that, in my opinion, an API exists to provide access to data, not an interface. I do not believe that internationalization or localization are concerns that should be applied on the API level. I also believe that different clients have different needs for displaying errors. Furthermore, if this is a third-party API, clients will each have a different tone as part of their user experience, and static error messages will not fit with that tone.

In brief, I believe that error messages are strictly the domain of a view, and APIs are decidedly models. I believe you should not pass through the API error message for the same reason you do not pass through your database's error message. The client has context the API does not, and therefore is better suited to creating a useful error message.

I'm not naive enough to believe I'll convince everyone that error messages should not be allowed. I think that developer error messages can be useful, assuming their target audience is client authors. If I were to be ambitious, I'd hope that I could convince people to relegate them to a relatively unobtrusive part of the spec as an optional component. Realistically, I just hope to convince people that they should not be a required component of the spec.

from json-api.

wrightling avatar wrightling commented on May 22, 2024

It seems like, while strictly passing strings for display to the user is a bad idea, the ability to do so should be preserved.

An example: you have an application with multiple front-ends (iOS, Android, Windows Mobile, browser, OS X app). Functionality is nearly identical, and you want to avoid duplicating localization/internationalization of most of the text shown to the users.

I'd rather localize the text server-side and avoid duplicating the code to localize it all within each client. Each client could still override/ignore any localizations that aren't relevant to them or need to be tweaked.

Perhaps its about time to pick some suggestions, such as jsdvaid's, and submit a pull request to get things going?

from json-api.

devinus avatar devinus commented on May 22, 2024

Please, for the love of all that is good and holy, include the key and the actual value that caused the error in the response.

from json-api.

paddycarver avatar paddycarver commented on May 22, 2024

@devinus that sounds like a recipe for trouble with very little gain. What does it enable that is otherwise impossible or difficult?

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

Relevant: http://www.mnot.net/blog/2013/05/15/http_problem?utm_source=dlvr.it&utm_medium=twitter

from json-api.

kjwierenga avatar kjwierenga commented on May 22, 2024

Looks like the http://tools.ietf.org/html/draft-nottingham-http-problem-03 draft handles this nicely indeed. It even handles internationalization. I don't like de camel-cased member names, but I guess that would be considered bikeshedding (sorry; had to use that word which I just learned about last weekend).

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

Also http://soabits.blogspot.dk/2013/05/error-handling-considerations-and-best.html

from json-api.

wrightling avatar wrightling commented on May 22, 2024

Interesting that neither of those articles Steve linked, nor the http-problem-03 draft try to tackle a partial success scenario or even mention returning multiple errors.

I'm very interested to see how we recommend returning errors when, say, request is sent to update multiple resources at once, and 3 out of 5 succeed, while the other two error.

from json-api.

diosney avatar diosney commented on May 22, 2024

Any updates on this? It seems that the discussion is kind of frozen now.

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

There haven't been any updates lately; the end of the year is a busy time, and Yehuda had an injury...

Expect to see these discussions move a lot next month, there'll be some announcements about it.

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

I've created a gist with some thoughts on API errors. It takes away with the concept of multiple errors. I think that there is only ever one reason for a failed request. Also, I suppose it's more compact than many of the previously proposed ideas.
https://gist.github.com/MajorBreakfast/8884211

from json-api.

diosney avatar diosney commented on May 22, 2024

Just for testing purposes I implemented in the API I'm working on a simple solution taken from the discussion above, something like:

{
    errors: [
        {
            code   : 'too_long',
            field  : '/posts/0/slug', // Empty if is a top-level, not resource-related error.
            message: 'Some message here.'
        },
        {
            code   : 'readonly_field',
            field  : '/posts/0/title',
            message: 'Some message here.'
        },
        {
            code   : 'some_other_code',
            field  : '', // A global error not applied to a resource.
            message: 'Some message here.'
        }
    ]
}

and until now I was able to easily accomodate all errors.

Now, I know that including an optional readable error message is a very shaking area but I like the idea. Imagine a situation where the client doesn't know what to do with a particular code error, so it could simple have at least a readable message to show it to users and they will be able to understand the error if they are not automated clients, in which case they can log it for further analisis by a human.

@MajorBreakfast:

These are some thoughts on errors response both considerations on your proposal and others mixed (I'm all but an errors response expert :D so take them easy).

I strongly think that there can be multiple reasons for errors, and hence multiple errors if we accept the convention to have only one error per reason. The same example you pointed out, validation, fit into this pattern and is very likely to not be the only one. Also, by having the convention of an errors array, its insertion in to the standard happens naturally and easen the processing the clients have to be done to get them. Besides, by flattening and standarizing the tree to three or four attributes needed (code,field,message) the automated processing in the client is simplified. Of course, you can always use meta for that.

As @mamund said, we should have to always report two levels of error information, one at the protocol-level (HTTP errors codes: 4xx and 5xx) and the other at the application-level (the errors section we are discussing now).

Also, I think that the standard shouldn't enforce developers the convention on how the errors codes should be formed, since this code can be one bubbled up by an lower layer that devs can't control or even devs from separate teams can have different rooted conventions and there will be objectivelly no gain to add this restriction (I could be wrong).

Anyways, I do think that all we have to resume this discussion since is a very important section of the spec.

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

Thanks for your response!

About your fields:

  • "message": If you have a smart error name, then the message is redundant. It's a pain to localize. And as people pointed out above, links to documentation and explanations don't belong into the API response. I think we should allow arbitrary fields. If you need a message field for your app, then use one. But I think that we should not encourage it.
  • "code": Just the wrong choice of word. A "type" or "name" is what we want. Code suggests something short like "RJ45" or "E42" - something nondescriptive.

About the flattening. Mabe we're onto something here. If it's flat, then the data framework (like ember-data) has an easier job to pipe the errors through to the place where they're needed. I like it.

About the "meta" field: I think we should simply reserve the keys "type" and "path" instead.

About the HTTP error codes: I agree. HTTP error codes are the way to go. What we're defining here is just additional information, so that the client side app can tell the user about what went wrong in greater detail.

About the error bubbling: It's quite a security risk to let arbitrary errors through. :)

About resuming the discussion: I totally agree. We have the chance to standardize something great here. And if we do it right, then it's even sane (unlike SOAP).

And finally how it could look like:

POST /users:

{
  "errors": [
    { "type": "required", "path": "/givenName" },
    { "type": "invalidName", "path": "/familyName" },
    { "type": "emailAlreadyInUse", "path": "/email" },
    { "type": "length", "path": "/password", "min": 8 },
    { "type": "zipCodeDoesNotMatch", "path": "/city" },
    { "type": "outOfErrors" },
    { "type": "errorAffectingAField", "path": "/city" },
    { "type": "errorAffectingAWholeDocument", "path": "/" }
  ]
}
  • MUST include a "type" which is a string and SHOULD NOT include the word "error"
  • SHOULD include a "path" to either a field or a document. If it's not present then the error is considered to be global.
  • MAY include other arbitrary fields that specify the error further. (-> "message" field)

Notice, that I use camelCase. Maybe we should recommend that (JSON = JavaScript Object Notation), but certainly not enforce it.

What do you think?
Should we call it "type", "errorType" or "problemType" (as in http://tools.ietf.org/html/draft-nottingham-http-problem-03 which was mentioned above)? I went for "type" because it's a single word.

from json-api.

guillec avatar guillec commented on May 22, 2024

I have been using http://tools.ietf.org/html/draft-nottingham-http-problem-06 for my errors which does have the disadvantage of not returning multiple errors. Although it does seem like in the future there could be a http_problems media type, mentioned in the comments of http://www.mnot.net/blog/2013/05/15/http_problem

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

@guillec Do you use a url as "type"?

from json-api.

guillec avatar guillec commented on May 22, 2024

@MajorBreakfast yup

On Sunday, February 9, 2014, MajorBreakfast [email protected]
wrote:

@guillec https://github.com/guillec Do you use a url as "type"?

Reply to this email directly or view it on GitHubhttps://github.com//issues/7#issuecomment-34587581
.

from json-api.

diosney avatar diosney commented on May 22, 2024

@MajorBreakfast Great! Lets continue to heat the discussion and expect the others to comeback to it since it was frozen for quite some time now :)

  • path instead of field: I like it! :)
  • message: I agree, If one have good errors ids it should be redundant. That being said, I think that a lot of devs will make a use of it. I like very much the idea of allowing arbitrary fields like a plain JSON+API document would have, and include in the standard only the really needed ones or at least the ones that all are agrees to be there, and I'm okey with message being the first of those kind of arbitrary fields :)
  • code: I really don't care about the attribute name, just picked the first suggested above. Besides that, I do think that non-descriptive codes must be allowed since they are related to the application profile and not to the media type itself, and the API devs are the only ones responsibles to give them meaning. Maybe the example was bad or "fetched by the hairs", as we said here, but the rationale behind it is still valid.

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

@diosney Glad you like it.

About the type field: I personally prefer something short like "type": "required" which I can directly use to look up a translated message (with some of the other fields as parameters, e.g. "min" length). But as @guillec said urls work just as well.

@steveklabnik Any comments on this?

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

Basically, we should use http://tools.ietf.org/html/draft-nottingham-http-problem-06 unless there is a significant problem with doing so. No reason to re-invent wheels.

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

I agree that reinventing the wheel just for the sake of reinventing it is wrong. However I have a few concerns about the "draft-nottingham-http-problem-06". The thing is: What matters in the end is what we can do with it in practice. We should design the API specification with simplicity in mind in such a way that the client side data framework authors can integreate it nicely. When using it we should have less work in total and it should encourage best practices.

The first thing I consider a problem is it not being an array. The usage of an error array means that the client side data framework can do the heavy lifting for us. It could place the errors for a field (-> "path") right next to it's value property.

Another thing I consider a mistake is that the "type" field has to hold an URL. It means that implementors have to create all these routes. For some public APIs that could make sense but for private APIs a README.md in the repo will do just as fine. I don't see the value for the extra work. It kind of reminds me of xml namespaces: A nice idea in theory but not a practical solution.

Also harmful is the encouragement of having a "title" and "detail" field. Both are nice to have but they're, asuming the "type" was chosen wisely, almost always redundant and they're not easily localizable on the client side because they're full sentences. The "type" field isn't well suited for usage as key in a language file either because it's a long URL. We should design the specification with client side localization in mind because the trend is towards web apps. In order to be future proof that is what we need to think about. The days where you simply showed the message from the server to the user in a message box are over anyway. For example if the user filled out a form it should specifically mark the fields that where filled out incorrectly. I really prefer the lightweight approach I described in the paragaph above with the "path" property being used to move the error to where it's needed and the rest is done through application logic.

And lastly the "instance" field. The JSON patch standard which we already use calls it "path". "instance" seems to be the wrong word for what it is, too.

Note: I added a few examples to the JSON in the post above.

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

I found another problem with the "path" field. What if the documents don't have ids yet? This is a problem if you post more than one thing at once.

Possible solution:

POST /users (Request)

{
  "users": [
    { "familyName": "Doe" },
    { "givenName": "John", "familyName": "123" }
  ]
}

POST /users (Response)

{
  "errors": [
    { "type": "required", "path": "/users/1/givenName" },
    { "type": "invalidName", "path": "/users/2/familyName" }
  ]
}

Notice that the "1" and "2" stand for the index in the array. (Even if they had a clientId assigend)

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

@MajorBreakfast I would encourage moving those discussions upstream and affecting that spec, rather than throwing it out and building Yet Another One. Those all sound very valid, so let's fix that spec, and then use it.

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

If that is possible - yes. Where does the discussion about that spec happen?

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

I think you found at least one of the right places. The place FOR SURE is on the IETF tracker.

from json-api.

celkins avatar celkins commented on May 22, 2024

@MajorBreakfast

Another thing I consider a mistake is that the "type" field has to hold an URL. It means that implementors have to create all these routes."

Except that it doesn't. Nothing in the spec excludes values for type such as the following:

Some values are obviously more useful than others.

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

You're of course right. It says that it should be an URI not an URL - my bad. What I'm proposing is still valid, though: I think that it should simply be a short string (that typically cannot be dereferenced). The example given should show something in camelCase, like "invalidEmail". "http://example.com/errors#invalidEmail" is super cumbersome by contrast. The "type" is meant to be used in your application code and/or language files. It's all about what's nicer to handle in code: A short string that brings it to the point wins, a long URI loses

from json-api.

diosney avatar diosney commented on May 22, 2024

I think we should already move on and define the errors within JSON+API standard itself like other media-types did instead of using another media-type for this, be draft-nottingham-http-problem-06 or another of the ones that currently are living out there.

This was already done with success by other media-types, like @mamund' collection+json, so there is no shame on doing that. I'm not saying that this is okey due other people did it, but there are problems with the other Errors standards that renders them incompletes as a json+api point of view and that some additions we would need for make them usable aren't desired parts of those standards or can have a bit of resistance to adopt it.

So , we can:

1- create another media-type for this and enlarge the zoo (paraphrasing @mamund).

or

2- include the errors standard in json+api itself.

I personally prefer 2, but I could live with whatever solution cames if it fill all the holes.

On draft-nottingham-http-problem-06, right now and after 6 revisions it still has several issues that slows its consideration to use it along json+api.

To sumarize some of them:

thanks to @guillec:

  • [its major hole IMHO] It only supports one single error per response and not an error collection, and according with the discussion, it is almost for sure it won't land into the media type. It was commented that was being into consideration the addition of a problems media-type, but I can't find any references to it 7 months later.

thanks to @MajorBreakfast:

  • The error type attribute (the one that holds the error code/id) must be an URI, which has some issues as pointed by @MajorBreakfast.

not commented here before (maybe are minor issues compared with the above) and that were pointed in the mnot blog comments:

  • Repetition of the HTTP status in the response body itself which can lead to out-of-sync states.
  • Force devs to use only camelCase attributes, which can be a source of discussion regarding the media-type adoption due conflicting code-style (that is a nonsense but can really happen).

So, what you think about all this nonsense?

from json-api.

MajorBreakfast avatar MajorBreakfast commented on May 22, 2024

I think that the standard MUST support camelCase, snake_case and dashes but it should RECOMMEND camelCase because that's very common in JavaScript (and the frontend is probably in JavaScript). I think it's a must because all three are quite common and frontend frameworks that support json api should be able to handle all three.

I agree that it's stupid to repeat the "statusCode" in the JSON. It simply doesn't belong there.

I posted new thoughts about the problems spec. here: mnot/I-D#45 (comment)

I think/agree that first and foremost it's essential for the errors spec we're going to end up using to be consistenent with the style of the rest of the spec and it should also address all the major use cases. That means it should support global errors, errors about an object in the request document and errors about a field of an object. In a year I'd like to be able to type something like {{input-field value=email errors=fieldErrors.email}} (Custom ember component that displays the errors right next to the input, controller is the UserController)

from json-api.

mnot avatar mnot commented on May 22, 2024

Answered over at mnot/I-D#45; thanks for the heads-up.

FWIW - the latest draft goes from camelCase to single words to avoid stylistic clashes.

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

I would encourage you all to check out #208 .

Basically, after some discussion, adding a simple error type to JSON API directly seems good. This also does not prevent you from serving vnd.error if you wish, but requiring a dependency on an additional specification seems unwise.

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

Adding to 1.0.

from json-api.

mnot avatar mnot commented on May 22, 2024

@steveklabnik - I support your effort to eradicate all other specifications. When will you be taking HTTP off my hands?

from json-api.

paddycarver avatar paddycarver commented on May 22, 2024

srsly

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

Mark, that's not fair and you know it. JSON API is built on top of a ton of existing RFCs already. This decision does not block anyone who wants to use a specific error media type with JSON API.

from json-api.

steveklabnik avatar steveklabnik commented on May 22, 2024

I added a new line to explicitly call this out.

from json-api.

devinus avatar devinus commented on May 22, 2024

@steveklabnik My fears haven't been assuaged. I think we need an errors key, i.e. multiple errors can come back from the backend.

from json-api.

mnot avatar mnot commented on May 22, 2024

@steveklabnik Fair? There is no fair in API's....

Sorry (for both!), couldn't resist.

from json-api.

wycats avatar wycats commented on May 22, 2024

@mnot fwiw, I am in favor of making sure that JSON API is extensible with other media types that are richer versions of the default behavior of embedded content.

In this case, I have proposed (and @steveklabnik agrees) a header (JSONAPI-Error-Type) that a server implementation can use to inform the client that it is using an alternate media type for errors. This would let simple clients know to ignore the embedded errors, and will allow the community to coordinate around common alternates that we can bake into the commonly used tools.

from json-api.

dgeb avatar dgeb commented on May 22, 2024

#237 introduces a new error object. Error objects SHOULD be returned in a collection keyed by "errors".

I was certainly influenced by @mnot's http://tools.ietf.org/html/draft-nottingham-http-problem-06 when designing the error object. However, I also felt it important that errors be valid resource objects themselves, and reference other resources through links.

I believe more examples of errors are needed in the spec, as evidenced by the discussion in #234. Let's close this general discussion though and track specifics in new issues.

from json-api.

jwachira avatar jwachira commented on May 22, 2024

There is so much insights and stuff to learn from this discussion; I would love to see some of your implementations if anybody is willing to paste some code here 👍

@steveklabnik @dgeb

from json-api.

zekefast avatar zekefast commented on May 22, 2024

I think as this issue was closed the (chapter in FAQ)[http://jsonapi.org/faq/#how-to-discover-resource-possible-actions] need to be updated.

from json-api.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.