Taru
Taru

Reputation: 2732

Symfony2 - Check if "application/json" is supported in Accept HTTP header

I'm using the Symfony2 framework for building a REST API,

I send the response to my clients using "application/json",

How can I check if applcation/json is supported in their HTTP request header?

Thank you.

Upvotes: 3

Views: 3810

Answers (3)

devsheeep
devsheeep

Reputation: 2116

Check the getAcceptableContentTypes method on the request object.

$acceptsJsonContent = in_array('application/json', $request->getAcceptableContentTypes());

Upvotes: 6

Anjana Silva
Anjana Silva

Reputation: 9201

The header of the json request should be like this.

headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

Back in controller you can filter the request to see whether it's coming through a xml/http content. (Such as Ajax)

if($request->isXmlHttpRequest())
{

    $result = json_encode($json);

    return new Response($result , 200 , array( 'Content-Type' => 'application/json' ));
}

Hope this helps.

Cheers!

Upvotes: 0

kix
kix

Reputation: 3319

When your client requests a response in an exact format, it should specify an Accept: header, see the HTTP/1.1 spec.

Upvotes: 0

Related Questions