PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 23, 2022

[FIXED] Symfony FOSRestBundle API - receives empty JSON Request body

 January 23, 2022     api, json, php, symfony     No comments   

Issue

I'm trying to build Symfony API with the bundle, but every request that I sent has empty body.

Controller:

class IndexController extends AbstractFOSRestController
{
    /**
     * @Rest\Post("/api/test", methods={"POST"})
     * @param Request $request
     * @return View
     */
    public function testError(
        Request $request
    ) : View {

        $requestData = $request->request->all(); // problem: requestData is []

        return View::create()
            ->setStatusCode(200)
            ->setFormat("json")
            ->setData(["data" => $requestData, "status" => "ok"]);
    }
}

I am sending this request from CURL:

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:8000/api/test

I've also tried sending it with Postman. I receive this response:

{"data":[],"status":"ok"}

Here is my fos_rest.yaml file:

fos_rest:
    view:
        view_response_listener: true
    format_listener:
        rules:
            - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json, html ] }
            - { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ html, json ] }

Solution

I think you forgot about proper serializer, which is mostly required. Here is my config, should help you with it:

fos_rest:
    serializer:
        serialize_null: true
    body_listener:
        enabled: true
        throw_exception_on_unsupported_content_type:  true
        decoders:
            json: fos_rest.decoder.json
    format_listener:
        rules:
            - { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/', priorities: ['html', '*/*'], fallback_format: html, prefer_extension: true }
    param_fetcher_listener: force
    view:
        view_response_listener: 'force'
        formats:
            json: true
    allowed_methods_listener: true
services:
    fos_rest.decoder.json:
        class: FOS\RestBundle\Decoder\JsonDecoder
        public: true

Manual

Symfony: Setting up the bundle, part B



Answered By - Karol Gasienica
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing