Home > other >  JSONAPI URL requirements for new resource
JSONAPI URL requirements for new resource

Time:08-24

According to JSON API V1 specification and its recommendations, I know the URLs for collection of resources should be something like /photos. And the URL for reading, updating, or deleting a single resource that already exists in the database should be something like GET, PATCH, DELETE /photos/:id, for example. But are there any URL requirements for rendering JSON data for resources to be created (i.e. the resource does not exist in DB yet and therefore it doesn't have id) yet. I know this is allowed in terms of the response data as section 5.2 says

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.

However, can the URL for rendering such a new object be like photos/new? As I'm using Ruby on Rails on the backend, photos/new is pretty typical.

Thanks!

CodePudding user response:

The JSON:API specification is agnostic about URL design. But it defines how given URLs should be used. For creation of resources the URL, which represents a collection of resources of that type should be used:

A resource can be created by sending a POST request to a URL that represents a collection of resources.

https://jsonapi.org/format/#crud-creating

If you use /photos URL for a collection of photos, you should support creating another photo resource on that endpoint.

The server must assign an ID to a resource on creation unless client-generated IDs are used. It should also inform the client about the URL representing the newly created resource both through self link of the resource as well as Location HTTP response header. Going forward a client should use that URL to fetch the resource.

However, can the URL for rendering such a new object be like photos/new?

I'm not sure what you mean. A resource, which has not been created yet, can not be fetched from a REST API.

The term "render" is not that common for REST APIs. Do you refer to responding with a JSON representation of a resource as "rendering"? In this case a REST API cannot "render" the resource before it has been created by the client.

URLs of clients are independent from the URLs used by a REST API. A client could render a form to create a new resource on end-user facing URL /photos/new, while using the /photos URL of the REST API to create that resource.

CodePudding user response:

Usually to create new object POST is using

You just pass resource attributes with request body. And you doesn't pass id

Modified example from your link

{
  "type": "photos",
  // no id here
  "attributes": {
    "title": "Rails is Omakase"
  }
}

And path for such request is /photos

In monolithic Rails app /new is just page to create some resource, you don't need such GET-route in the JSON API

  • Related