Skip to content

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

Open
@obulat

Description

@obulat

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 {}.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestopenapi-fetchRelevant to the openapi-fetch library

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions