6

I created a little crud system with a OneToMany relationship and want to create a little api as well.

I generated a new ApiBundle and added 1 controller for 1 of my entities that looks like this:

<?php

namespace ApiBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use DataBundle\Entity\Job;

class JobController extends FOSRestController
{
    public function getAction()
    {
        $result = $this->getDoctrine()->getRepository('DataBundle:Job')->findAll();

        if ($result === null) {
            return new View("There are no jobs in the database", Response::HTTP_NOT_FOUND);
        }

        return $result;
    }

    public function idAction($id)
    {
        $result = $this->getDoctrine()->getRepository('DataBundle:Job')->find($id);

        if($result === null) {
            return new View("Job not found", Response::HTTP_NOT_FOUND);
        }

        return $result;
    }

}

But when I make a call to /api/jobs i get the following error:

Uncaught PHP Exception LogicException: "The controller must return a response (Array(0 => Object(DataBundle\Entity\Job), 1 => Object(DataBundle\Entity\Job)) given)."

Anyone has any idea what I am doing wrong here?

Any help is appreciated!

Many thanks in advance :)

1

3 Answers 3

8

The error is telling you to return a response. Something like this:

return new Response(
        'There are no jobs in the database', 
         Response::HTTP_OK
    );

or if you want a json response you can do something like this

return new JsonResponse(
         [
             'message' => 'There are no jobs in the database', 
         ]
         Response::HTTP_OK
    );
Sign up to request clarification or add additional context in comments.

Comments

0

Controller must return an Response object, you are returning the $result.

Comments

-1

Can you try this:

$view = $this->view($result, Response::HTTP_OK);
return $view;

Let us know if that works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.