Search code examples
json-apijsonapiframework

JSON API - How to form URI segments when fetching data from external source


I'm writing an api specification which complies to https://jsonapi.org/format/ standard. I have trouble identifying the correct uri format to implement in below scenario.

Overview:

Company Inventory system contains product and price information. one product has many prices. Inventory system push data to local system via an API but using inventory system Primary key. Local system should capture provided data into the API and update or create price records in local db

eg:

POST /products/..... ?? or POST /products/

{
   "data":{
       "externalId":"EIR-32432",
       "externalPriceId":xxx,
       "price":"xxx.xx",
       "currency":"USD"
   }
}

Solution

  • You must send a POST request to the URL that represents a collection of that resources to create a resource in JSON:API specification:

    A resource can be created by sending a POST request to a URL that represents a collection of resources. The request MUST include a single resource object as primary data. The resource object MUST contain at least a type member.

    The specification itself is agnostic about URL naming but uses pluralized resource type in all examples. If you are following the same convention, a request to create a product should be POST /products.

    As said in above quote the request must include a resource object. The example in your question is not a valid resource object as it misses a type and the attributes are not under attributes key. A valid resource object to a create a product would look like:

    {
        "data":{
            "type": "products",
            "attributes": {
                "externalId": "EIR-32432",
                "externalPriceId": "xxx",
                "price": "xxx.xx",
                "currency": "USD"
            }
        }
    }
    

    Please also note that relationships should not appear as attributes:

    Although has-one foreign keys (e.g. author_id) are often stored internally alongside other information to be represented in a resource object, these keys SHOULD NOT appear as attributes.

    It's not quite clear from your example if externalId and externalPriceId are relationships in the scope of your API or not.

    Please find more details about create a resource in JSON:API in the specification itself: https://jsonapi.org/format/#crud-creating It also comes with an example.