dio icon indicating copy to clipboard operation
dio copied to clipboard

JSON API requests are not parsed by default as JSON

Open kirhgoff opened this issue 5 years ago • 6 comments

New Issue Checklist

  • [v] I have searched for a similar issue in the project and found none

Issue Info

Info Value
Platform Name flutter
Platform Version 2.0.3
Dio Version 4.0.0-prev3
Android Studio / Xcode Version 4.1.2
Repro rate 100% - logic issue
Repro with our demo prj Requires different server
Demo project link explanation should be enough

Issue Description and Steps

Here is generated (by retrofit) dio call (absolutely same code works for the endpoint that returns application/json)

  Future<SampleResponse> fetchSavedJobs(userId) async {
    const _extra = <String, dynamic>{};
    final queryParameters = <String, dynamic>{};
    final _data = <String, dynamic>{};
    final _result = await _dio.fetch<Map<String, dynamic>>(
        _setStreamType<SampleResponse>(Options(
                method: 'GET',
                headers: <String, dynamic>{r'Content-Type': 'application/json'},
                extra: _extra,
                contentType: 'application/json')
            .compose(_dio.options, '/users/$userId/saved_jobs',
                queryParameters: queryParameters, data: _data)
            .copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl)));
    final value = SampleResponse.fromJson(_result.data!);
    return value;
  }

The issue is very simple - if the response is sent from JSON API server, the content type will be application/vnd.api+json; charset=utf-8 (see https://jsonapi.org/format/). The data in the response is formatted as JSON, but it won't get parsed as JSON. The code in DefaultTransformer here https://github.com/flutterchina/dio/blob/0bf69c8ebd7e8c010345feb20034450839571eda/dio/lib/src/transformer.dart#L153-L155 will return false.

Basically, this is the problem MediaType.parse('application/vnd.api+json; charset=utf-8').mimeType != Headers.jsonMimeType.mimeType

There is a workaround through interceptors, but it would be nice to have it working out of the box, as it is the same JSON, just a different content type. In the worst case, could _isJsonMime method made public so it is easy to override it?
https://github.com/flutterchina/dio/blob/0bf69c8ebd7e8c010345feb20034450839571eda/dio/lib/src/transformer.dart#L166-L170

Or more loose JSON detection?

kirhgoff avatar Mar 29 '21 02:03 kirhgoff

I feel application/vnd.api+json should be treated as a new MIME, rather than the standard json MIME. It is a new thing customised by JSONAPI, which isn't standard.

To support JSONAPI, a new transformer can be introduced, and in the implementation, it can handle the body as JSON. And potentially, with some schema verification if needed, to ensure the body is comply to the JSON API spec.

timnew avatar Mar 29 '21 02:03 timnew

In this case, you can convert response data to json in response interceptor.

wendux avatar Apr 01 '21 12:04 wendux

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, please make sure it is up to date and if so, add a comment that this is still an issue to keep it open. Thank you for your contributions.

stale[bot] avatar Jun 04 '21 15:06 stale[bot]

hey, i found a solution for this...

i create my transformer and just override the response headers.

in this case: if (responseBody.isNotEmpty && options.responseType == ResponseType.json && _isJsonMime(response.headers[Headers.contentTypeHeader]?.first)) {

will return true.

class MyTransformer extends DefaultTransformer {

  @override
  Future<String> transformRequest(RequestOptions options) async {
      return super.transformRequest(options);
  }


  @override
  Future transformResponse(
      RequestOptions options,
      ResponseBody response,
      ) async {
  response.headers['content-type'] = ['application/json'];
    return super.transformResponse(options, response);
  }
} 

and use it

dio.transformer = MyTransformer();

nirbar89 avatar Aug 02 '21 08:08 nirbar89

This is the code I'm using


import 'dart:convert';

import 'package:dio/dio.dart';

import 'network_constants.dart';

class JsonApiEncoderInterceptor extends Interceptor {
  JsonApiEncoderInterceptor();

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (_isJsonApi(options.contentType)) {
      options.data = json.encode(options.data);
    }

    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    final contentType = response.headers.value(Headers.contentTypeHeader);

    if (_isJsonApi(contentType)) {
      response.data = json.decode(response.data.toString());
    }

    handler.next(response);
  }

  bool _isJsonApi(String? contentType) =>
      contentType?.startsWith(jsonApiContentType) ?? false;
}
// network_constants.dart
import 'package:dio/dio.dart' as dio;
import 'package:retrofit/retrofit.dart';

const jsonApiContentType = "application/vnd.api+json";

const jsonApiPostHeader = Headers(<String, dynamic>{
  dio.Headers.contentTypeHeader: jsonApiContentType,
});

const restApi = RestApi();
const multiPart = MultiPart();
const body = Body();
const part = Part();
const sendProgress = SendProgress();
const cancelRequest = CancelRequest();

timnew avatar Aug 02 '21 11:08 timnew

@timnew

I feel application/vnd.api+json should be treated as a new MIME, rather than the standard json MIME. It is a new thing customised by JSONAPI, which isn't standard.

I'm afraid I disagree. See https://en.wikipedia.org/wiki/Media_type#Suffix and https://datatracker.ietf.org/doc/html/rfc6839#section-3.1. Media types with the suffix +json are structured as 'application/json' and should be processed as such.

I need to call an API that uses "Media Type Versioning" (as explained here: https://www.baeldung.com/rest-versioning)

guldner avatar Feb 05 '22 12:02 guldner