Skip to content

Proposal: Response.json helper #1389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
lucacasonato opened this issue Jan 27, 2022 · 16 comments · Fixed by #1392
Closed

Proposal: Response.json helper #1389

lucacasonato opened this issue Jan 27, 2022 · 16 comments · Fixed by #1392
Labels
addition/proposal New features or enhancements needs implementer interest Moving the issue forward requires implementers to express interest topic: api

Comments

@lucacasonato
Copy link
Member

lucacasonato commented Jan 27, 2022

The Response object currently has a Response.redirect helper method to create Response objects with preset Location headers. Request and Response already have a json prototype method that allows parsing bodies as JSON, but there is currently no trivial one-liner to create JSON Response objects directly from a POJO.

I propose the addition of a Response.json(obj, opts) static method that creates a Response object with a body string containing the JSON serialized representation of obj. opts would allow further modification of the JSON response, namely setting headers and status code. By default the status code is 200, and the headers are the default response headers + content-type: application/json.

interface Response {
  [NewObject] static Response json(any object, optional ResponseInit init = {});
}

The motivation for this addition is that in server side runtimes using WHATWG Request and Response objects, folks often create helper methods for this behaviour that need to be duplicated across each project. This being built in would be very useful.

Thoughts?

Implementer interest:

  • Chromium ✔️
  • Firefox ✔️
  • Safari ❔
  • Deno ✔️
  • Cloudflare Workers ✔️
@annevk annevk added addition/proposal New features or enhancements needs implementer interest Moving the issue forward requires implementers to express interest topic: api labels Jan 27, 2022
@jasnell
Copy link

jasnell commented Jan 27, 2022

Yeah, Workers would be interested in this!

@lucacasonato
Copy link
Member Author

If Response.json does not work due to the conflict with the prototype json method, I'd also be happy with a Response.fromJSON.

@leerob
Copy link

leerob commented Jan 28, 2022

Vercel would be interested in this!

@Jarred-Sumner
Copy link

Bun would be interested in this!

@fabiancook
Copy link

Following, to replace the code here

The current minimum:

    respondWith(
        new Response(JSON.stringify({
            data: "value!"
        }), {
            headers: {
                "Content-Type": "application/json"
            }
        })
    )

This would reduce the code to:

    respondWith(
        Response.json({
            data: "value!"
        })
    )

Looks great 👍🏻

fabiancook added a commit to opennetwork/http-representation that referenced this issue Jan 28, 2022
fabiancook added a commit to opennetwork/http-representation that referenced this issue Jan 28, 2022
@mjackson
Copy link

Remix already implements this and it’s super handy. 👍

@SukkaW
Copy link

SukkaW commented Jan 29, 2022

Is it handy? Obviously yes. Is it good? Probably not.
If Response.json is added, sooner or later we will have to add Response.arrayBuffer, Response.blob, Response.text / Response.string (And maybe some people / companies even want Response.formData).

@fabiancook
Copy link

It would make sense to include all these others.

For Response.arrayBuffer we would use the default header Content-Type: application/octet-stream.

For Response.blob, grab from blob.type

For Response.text we could use text/plain by default, while still allowing Content-Type: text/html to be passed through init

And for Response.formData, Content-Type: multipart/form-data

@lucacasonato
Copy link
Member Author

Is it handy? Obviously yes. Is it good? Probably not.
If Response.json is added, sooner or later we will have to add Response.arrayBuffer, Response.blob, Response.text / Response.string (And maybe some people / companies even want Response.formData).

@SukkaW No need to add those, as those already exist. They are overloads of the new Response constructor. Example:

const resp = new Response(new ArrayBuffer(5));
const resp = new Response(new Blob(["hello world"]));
const resp = new Response("foo bar");
const resp = new Response(new FormData());

The only reason JSON can't be included in the overload is that the plain object can not be differentiated from other object inputs in a non confusing manner.

@jimmywarting

This comment was marked as off-topic.

@annevk

This comment was marked as resolved.

annevk pushed a commit that referenced this issue May 18, 2022
A method that can be used to create well-formed JSON responses with very little effort.

The JSON response is not pretty printed.

Tests: web-platform-tests/wpt#32825.

Closes #1389.
@ricea
Copy link
Collaborator

ricea commented May 24, 2022

JFYI, I requested a W3C TAG review of this feature in preparation for shipping in Chrome: w3ctag/design-reviews#741

@zcorpan
Copy link
Member

zcorpan commented Jun 8, 2022

I'll note that at least the Geometry API has static methods with fromX naming scheme, e.g.:

https://drafts.fxtf.org/geometry/#dommatrix

It seems easier to find the right documentation between Response.json and Response.prototype.json if they have different names.

Response.json(obj) is slightly easier to type than Response.fromJSON(obj), though personally I think the latter is more obvious what it does.

@whatwg whatwg deleted a comment from gliccowayne Jun 8, 2022
@silverwind
Copy link

silverwind commented Dec 12, 2022

I find the naming of this highly confusing. MDN for example lists Response.json which is actually Response.prototype.json and not this static method. Naming it Response.from or Response.fromJSON would be in line withArray.from. W3C has similar concerns.

@annevk
Copy link
Member

annevk commented Dec 13, 2022

That is being tracked by mdn/content#21550. I think this has shipped so I don't think we're in a position to rename.

I think the name is reasonable and consistent with other names on the object. That it pushes the ecosystem to no longer conflate statics and non-statics is a bonus.

@karlhorky
Copy link

I proposed that types for the Response.json() static method be added to TypeScript over here:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
addition/proposal New features or enhancements needs implementer interest Moving the issue forward requires implementers to express interest topic: api
Development

Successfully merging a pull request may close this issue.