سؤال

I'm building a Restful API and trying to use JSON:API format for my response. Looking at https://jsonapi.org/format/, it states:

A resource object MUST contain at least the following top-level members:

  • id
  • type

Exception: The id member is not required when the resource object originates at the client and represents a new resource to be created on the server.

My API will be returning a list of, say, fruits. The list of fruits won't be coming from my database -- it will be collected from an external source. That external source does not give me an id. Also, I won't be saving the fruit items in my database, so I can't even return an internally generated id for it.

Also, my database won't have a "fruits" table at all -- so I'm even reluctant to use the type member.

In other words, I don't think I can set id and type. And if I don't, then my API response is no longer JSON:API compliant.

How do I handle this?

هل كانت مفيدة؟

المحلول

It does not state, how the id shall look (apart from it being strings), i.e. you can use any uniquely identifing element in the object. Thus, for your fruit, I guess you have something like a name "apple", "orange", "melon": just use that as the id (as long as it is unique.)

For the type: just add fruit.

نصائح أخرى

If I understand correctly, you have an external source that gives you a list of items. These items, nor the list have any id.


Pretend the external source is a second database. This second database has a table. This table only ever has one item in it, and it is never the same one. Of course, the system cannot add or modify the table (you can think of it as not having privileges if you want). All that anybody can do is query the only item (which is never the same one) in the table.

This lone item in the table of the second database has an id. However, remember that the table never has the same item again, and thus the id is always different. Whatever it returned the last time? Deleted. We did not store it.

About the type... well, it is a table, just in another database (which happens to be read only). It must have a type.


You are going to generate the id using unix time or similar.

In practice the type would be for the benefit of the consumer of the API. I don't think the consumer should worry about whatever or not the data comes from your database. Just invent one. Say "fruit".


If it is possible to ask for a resource of that type by id... well, it does not exist anymore, it was deleted. 404 Not Found. Any other operation, is not supported. 403 Forbidden.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top