Mejores errores / Better API errors

  • August 24, 2017
  • Ismael Celis

Castellano

Durante los próximos días lanzaremos optimizaciones en la forma en que representamos errores en esta API.

Como antes, la mayoría de los errores de validación retornarán un estatus HTTP 422.

Un cambio que pudiera causar problemas en integraciones existentes es que ahora los mensajes de errores incluirán la ruta completa, dentro del input JSON provisto por el cliente, a la propiedad inválida.
Estas rutas serán representadas usando expresiones JSON path.

Por ejemplo, al enviar una estructura de datos para actualizar un producto y sus variantes:

{
  "variants": [
    {
      "title": "Variant 1",
      "stock": 1
    },
    {
      "title": "",
      "stock": 2
    }
  ]
}

La API retornaría la siguiente respuesta:

Antes de este cambio

{
  "_embedded": {
    "errors": [
      {
        "field": "variant.title",
        "messages": [
          "cannot be blank"
        ]
      }
    ]
  }
}

Después de este cambio

{
  "_embedded": {
    "errors": [
      {
        "field": "$.variants[1].title",
        "messages": [
          "is required and value must be present"
        ]
      }
    ]
  }
}

La expresión $.variants[1].title en el campo field nos dice que el título de la segunda variante en los datos enviados es inválido. El cliente puede procesar esa expresión para ubicar y corregir el elemento preciso en el input.

Esta API usará la “notación de puntos” de JSON Path, donde los objetos en una estructura son separados por puntos, y los arrays indexados por [].
Por lo tanto, $.variants[1].title en lugar de $["variants"][1]["title"]

Validación consistente de parámetros de tipo fecha

Algunos puntos de entrada en esta API aceptan fechas como filtros o parámetros (ej. ?pending_on_gte=2017-08-20).

Antes, validádamos estos parámetros de forma inconsistente (algunos retornaban estatus 500, otros simplemente ignorában fechas inválidas).

Ahora, si el cliente provee una fecha inválida (ej. ?pending_on_gte=lalala), todos los parámetros de fecha retornarán estatus 422 y mensajes de error según las convenciones descritas arriba.
Las fechas deben ser cadenas válidas en formato ISO 8601.

{
  "_embedded": {
    "errors": [
      {
        "field": "$.pending_on_gte",
        "messages": [
          "must be a valid date in format ISO 8601"
        ]
      }
    ]
  }
}

No anticipamos disrupciones mayores para la mayoría de integraciones luego de este cambio, pero rogamos ponerse en contacto si piensan que su código podría ser afectado por eso.

Ismael

Equipo Bootic.

English

In the next few days we’ll be deploying some optimizations to how errors are represented in this API.

As before, most validation errors will return an HTTP status 422.

One possibly breaking change of note is that errors will not include the full path to each offending property within a JSON payload, using JSON path expressions

For example, when sending the following data structure to update a product with variants:

{
  "variants": [
    {
      "title": "Variant 1",
      "stock": 1
    },
    {
      "title": "",
      "stock": 2
    }
  ]
}

… You would get the following error response:

Before

{
  "_embedded": {
    "errors": [
      {
        "field": "variant.title",
        "messages": [
          "cannot be blank"
        ]
      }
    ]
  }
}

After

{
  "_embedded": {
    "errors": [
      {
        "field": "$.variants[1].title",
        "messages": [
          "is required and value must be present"
        ]
      }
    ]
  }
}

The JSON Path expression $.variants[1].title in the field message now tells us which variant was invalid in the data structure provided in the request. Clients can process the path to point and fix the precise element in the payload.

We’ll use JSON Path’s “dot notation”, where objects are separarated by dots and arrays indexed by []. So $.variants[1].title and not $["variants"][1]["title"].

Consistent validation of date parameters

Some endpoints expect date filters, ex. /v1/shops/123/orders?pending_on_gte=foobar

Before, f you passed an invalid date (ex ?pending_on_gte=foobar) we were validating some of them (status 500 in some cases). Others were being simple ignored.

Now, all date filters will be validated (they must be valid date strings in ISO 8601 format).

If invalid, the API will return 422 responses and error information using the JSON path expressions described above. Example:

{
  "_embedded": {
    "errors": [
      {
        "field": "$.pending_on_gte",
        "messages": [
          "must be a valid date in format ISO 8601"
        ]
      }
    ]
  }
}

We don’t expect these changes to be disruptive to most clients, but please let us know if you think your integration is going to be affected by this.

Ismael

Bootic Team