1

I have a decoupled drupal project with an angular 5 front end that is utilizing a restful api to store data. Because this API needed a key that we didn't want to expose we have created a restful endpoint in the Drupal code that acts as a sort of proxy. The front end hits Drupal, Drupal adds the key, hits the api, and then Drupal returns the api's response to the front end.

When I hit the API directly, I get clean JSON:

{"total":610,"results": .....

But when I use the proxy, I get encoded json:

"{\u0022total\u0022:610,\u0022results\u0022:[{\u0022_id\u0022:\u .....

My Angular request:

get(): Observable<RecipePreview[]> {
    let encryptedAuthorizationString = 'BLAHBLAHBLAH';
    const headers = new HttpHeaders()
        .set("Content-Type", "application/json")
        .set("X-CSRF-Token", this._HttpServiceService.csrfToken)
        .set("Authorization", "basic " + encryptedAuthorizationString)
    ;

    let u = this.filter.url();

    return this._http.get(u,{headers})
        .map(res => {
                return res;
            }
        )
    ;
}

The Drupal RESTful endpoint code looks like this:

/**
 * Responds to entity GET requests.
 * @param $data
 * @return \Drupal\rest\ResourceResponse
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
public function get() {
    $url="BLAHBLAHBLAH";

    $client = \Drupal::httpClient();
    try {
        $request = $client->request('GET', $url, [
            'headers' => [
                'Content-Type' => 'application/json',
                'apikey' => "BLAH-BLAH-BLAH"
            ],
        ]);

        $file_contents = $request->getBody()->getContents();
    }
    catch (RequestException $e) {
        //An error happened.
        $file_contents = "There was an error.";
    }

    \Drupal::logger('Proxy API')->debug($file_contents);

    return new ResourceResponse($file_contents);
}

I'm pretty sure that ResourceResponse is doing something to the json, and there has got to be a way to tell it to not do it anymore? But how? Thoughts?

I'm also using the same final end point in a drupal content migration from source and I believe this formatting is causing issues with that as well.

Thanks so much for helping me out with this!

  • Is it double encoded? – Kevin Aug 3 '18 at 17:39
  • You could simply return a Symfony JsonResponse, I think there is no code in Drupal interfering with this response. – 4k4 Aug 3 '18 at 18:42
0

Kevin was on to it. It was being double encoded. I have to return a response, so I decode the results from the first api, then return it as a json response:

return new JsonResponse( json_decode($file_contents) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.