Skip to content

Automatically encode the body when "Accept": "application/x-www-form-encoded" header is passed #2069

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

Open
obulat opened this issue Dec 26, 2024 · 5 comments · May be fixed by #2096
Open

Automatically encode the body when "Accept": "application/x-www-form-encoded" header is passed #2069

obulat opened this issue Dec 26, 2024 · 5 comments · May be fixed by #2096
Assignees
Labels
enhancement New feature or request openapi-fetch Relevant to the openapi-fetch library

Comments

@obulat
Copy link

obulat commented Dec 26, 2024

Problem

For the endpoints requiring x-www-form-encoded body parameters, the request body is serialized as a string, and then sent as an empty object string {}. The solution is to provide a custom body parser that converts the plain object of the body into URL-encoded string. This is not documented, and is difficult to debug.

Possible solutions

  1. The simplest solution would be to document the need to pass a custom bodySerializer.

  2. A better solution would be to automatically encode the body if the header is passed.
    The default defaultBodySerializer could accept the fetchOptions.headers parameter, and return new URLSearchParams(body).toString if the "Accept": "x-www-form-encoded" header is passed by the user.

/**
* Serialize body object to string
* @type {import("./index.js").defaultBodySerializer}
*/
export function defaultBodySerializer(body) {
if (body instanceof FormData) {
return body;
}
return JSON.stringify(body);
}

  1. Even better would be to automatically infer when the endpoint requires encoded body from the OpenAPI types, and automatically encode it, even without the need to set the header.

Additional context

I ran into this problem when working on @openverse/api-client. Openverse API uses Django OAuth Toolkit for authentication, and the token requests require the body to be url-encoded. The API requests from the api-client were failing due to invalid_grant_type. Turned out that the request was sending an empty body {}.

@drwpow
Copy link
Contributor

drwpow commented Jan 3, 2025

Thanks for suggesting. I’m not opposed to adding an additional check here, if that would satisfy this. Just to clarify, are you proposing something like the following?

  export function defaultBodySerializer(body) {
-   if (body instanceof FormData) {
+   if (body instanceof FormData || body['x-www-form-encoded']) {
      return body;
    }

Even though this is technically a nonstandard parameter, this does seem common enough where it’s cheap to support so I’d be open to it. I think we could also append to the docs explaining this as well. Does that match your thinking?

@obulat
Copy link
Author

obulat commented Jan 4, 2025

Thanks for suggesting. I’m not opposed to adding an additional check here, if that would satisfy this. Just to clarify, are you proposing something like the following?

  export function defaultBodySerializer(body) {
-   if (body instanceof FormData) {
+   if (body instanceof FormData || body['x-www-form-encoded']) {
      return body;
    }

Even though this is technically a nonstandard parameter, this does seem common enough where it’s cheap to support so I’d be open to it. I think we could also append to the docs explaining this as well. Does that match your thinking?

I think we cannot get the Accept header from the body. So, it would be necessary to also pass the headers to the defaultBodySearializer, something like this:

export function defaultBodySerizlier(body, headers) {
  ...
  if (headers.get("Accept") === "x-www-form-encoded") {
    return new URLSearchParams(body).toString()
  }
  ...
  return body
}

@drwpow
Copy link
Contributor

drwpow commented Jan 4, 2025

Ah that’s doable. Wasn’t sure if it was a header param or something passed in the request body. Would accept a PR for this with tests! If additional work is needed we may have to discuss tradeoffs, but right now this seems “free” both in runtime and code size so no reason not to!

@obulat
Copy link
Author

obulat commented Jan 6, 2025

I will try to open a PR this week.

Our use case for this in Openverse is sending the token request to a Django Rest Framework API with the following schema:
https://github.com/WordPress/openverse/blob/bce7ccb80e55ab66b81d9ca1a9f6af2d710a73d5/packages/js/api-client/src/generated/openverse.ts#L1397-L1408

Ideally, I would prefer to send the request like the one below, and have openapi-fetch understand from the OpenAPI schema that the body needs to be URL-encoded (based on requestBody: { content: { "application/x-www-form-urlencoded": components["schemas"]["OAuth2TokenRequest"] })

fetch(url, body: { clientId: someClientId, clientSecret: someClientSecret })

But I don't think the fetch function has access to the OpenAPI schemas for the specific paths, does it?

@drwpow
Copy link
Contributor

drwpow commented Jan 6, 2025

But I don't think the fetch function has access to the OpenAPI schemas for the specific paths, does it?

It doesn’t; that’s the tradeoff with openapi-fetch. In order to have the actual OpenAPI schema in runtime, you’d need to pay a cost of heavy client weight and memory usage. But there’s almost always a way to get TypeScript to throw an error that tells the user they need to pass in X, Y, and Z settings that lead to the result you want

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request openapi-fetch Relevant to the openapi-fetch library
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants