0
votes

I am confused about for which situation I am defining the properties in my json schemas.

Assume I have an item product for which I am trying to define a schema. In my database the products table has id, brand_id, name, item_number and description. All except description are required fields. The id is autogenerated by the database and the brand_id is set upon creation automatically by the api based on the user creating.

This means I can POST /api/products using only the following data:

{
  "product": {
    "name": "Product Name",
    "item_number": "item001"
  }
}

However, how should I now define the product schema? Should I include the properties id and brand_id? If so, should I label them as required, even though they are set automatically?

This is what I came up with:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://jsonschema.net/products",
  "type": "object",
  "properties": {
    "item_number": {
      "id": "http://jsonschema.net/products/item_number",
      "type": "string"
    },
    "name": {
      "id": "http://jsonschema.net/products/name",
      "type": "string"
    },
    "description": {
      "id": "http://jsonschema.net/products/description",
      "type": "string",
      "default": "null"
    }
  },
  "required": [
    "item_number",
    "name"
  ]
}
1

1 Answers

2
votes

You should only define in your JSON schema properties that are dealt with by the user of the API.

In your case, it makes no sense to have id and brand_id in the schema that defines the POST body entity for the creation of a new product because these values are not provided by the API user.

This said, you may have another schema for existing product entities where these two fields are present, if it's OK to expose them publicly.

If that's the case, for this you can use schema union mechanism and have the "existing product" schema use allOf new_product.json and add id and brand_id to it.