7 - PHP MVC Frameworks REST Controllers and Routing Lab
7 - PHP MVC Frameworks REST Controllers and Routing Lab
Responses
This document defines a complete walkthrough of creating a REST API for our Blog application,
from setting up the serializer bundle, creating our own API bundle, ending up with fully
functioning REST API.
The command will download the bundle and include it automatically to the autoloader. You don’t
need to include anything anywhere.
Similar to this, we should create 2 more fields for the “content” and “date”. Here is how we
create them:
…
DATABASE_URL=mysql://root:@127.0.0.1:3306/blog_rest_api?
serverVersion=mariadb-10.4.11
Now, you should see the table “article” is created in the database “blog_rest_api”
/**
* @Route("/articles", methods={"GET"}, name="rest_api_articles")
*/
public function articlesAction()
{
// Get all articles in Database
$articles = $this->getDoctrine()->getRepository(Article::class)->findAll();
To test the first action, type the following command to run the local server:
// Article found
$json = $this->serializer->serialize($article, 'json');
return new Response(
$json,
Response::HTTP_OK,
array('content-type' => 'application/json')
);
}
The code is pretty much the same as previous one with a little difference.
If requested article is not found Response object is returned containing error message encoded in
JSON
The Response code for not found resources is 404 or in Symfony
Response::HTTP_NOT_FOUND
For successful requests response code should be 200 OK .
In Symfony - Resonse::HTTP_OK
Create new action: createAction() - responsible for creating new articles
/**
* @Route("/articles/create", methods={"POST"}, name="rest_api_article_create")
*/
public function createAction(Request $request)
{
try {
// Get data in Request from client
$article = new Article();
$data = json_decode($request->getContent(), true);
$article->setTitle($data['title']);
$article->setContent($data['content']);
$article->setDate(\DateTime::createFromFormat('Y-m-d', $data['date']));
$statusCode = Response::HTTP_NO_CONTENT;
}
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();
$statusCode = Response::HTTP_NO_CONTENT;
}
return new Response(null, $statusCode);
}