Skip to main content

Symfony2 Creating a REST API Part 1

Symfony2 Creating a REST API Part 1


Introduction

This tutorial aims to get someone who is completely new to Symfony2 setup with a very basic REST API with Symfony, from scratch, as quickly and as simply as possible.

The majority of this tutorial is based on the video below, which I found to be incredibly useful, but far too quick to follow which resulted in me creating this tutorial. This tutorial will also be kept up-to-date and fix some of the issues that have since arisen due to updates.

Steps

Defines

Firstly, register some variables in your shell that we will use throughout this tutorial


# Specify a name for your project
PROJECT_NAME="test_project"

# This should be the name of your organization, or your personal pseudonym
USERNAME="Programster"

# This must end with "Bundle" and use Camelcase
BUNDLE_NAME="DemoBundle"

Run the following commands to create a project


mkdir $PROJECT_NAME
cd $PROJECT_NAME
curl -s https://getcomposer.org/installer | php
sudo php composer.phar create-project symfony/framework-standard-edition ./$PROJECT_NAME 2.5.*
We use sudo in the command above to removes the possible ErrorException
mkdir: permission denied

Answer the Questions

At this point it will ask you a series of questions. I elected to NOT install the Acme demo bundle and use the mysqli database_driver. When the secret option comes up, make sure to create something new and write it down for now


sudo chown -R $USER:$USER $PROJECT_NAME
cd ./$PROJECT_NAME

Run the following commands to include some relevant bundles


composer require jms/serializer-bundle @stable
composer require friendsofsymfony/rest-bundle @stable
Those commands will automatically add the corresponding lines to the composer.json file.

Create A New Bundle

Run the following command to create a new bundle

php app/console generate:bundle
$USERNAME/$BUNDLE_NAME
You will not be able to use the variable names directly, but have to manually convert them into the corresponding strings for entry!

Press return three times to use the defaults for the questions that come next.


Bundle Namespace:
Bundle name:
Target directory:
For configuration format, I chose php. Then choose no to generating the whole directory structure and choose yes to confirm generation. Confirm automatic updating of your kernel and routing.

Register the bundles with Symfony.

editor app/AppKernel.php
Add the following two lines to the bundles array

new JMSSerializerBundleJMSSerializerBundle(),
new FOSRestBundleFOSRestBundle(),

Your file should now look similar to the one below:

Create A User Entity


cd src/$USERNAME/$BUNDLE_NAME
../../../app/console doctrine:generate:entity

Answer the Questions:

Video reference point
  • The Entity shortcut name: $USERNAME$BUNDLE_NAME:User
  • accept annotation as the configuration format
  • Add the following fields
  • username string 255
  • password string 255
  • email string 255
  • Press return to stop entering fields
  • Press return to use "no" for "Do you want to generate an empty repository class"
  • Press return to confirm generation.

Define Configurations

Video reference point
Run the following command to append to the end of your config.yml file.

echo "
sensio_framework_extra:
view: { annotations: false }
router: { annotations: true }

fos_rest:
format_listener:
rules:
- prefer_extension: false
view:
view_response_listener: true
" >> ../../../app/config/config.yml
Please note that this is different from what is shown in the video. This was taken from a stack overflow post.

Define Our First Controller

editor ../../../app/config/routing.yml
Add the following:
users:
type: rest
resource: $USERNAME$BUNDLE_NAMEControllerUsersController

editor Controller/UsersController.php
<?php

namespace $USERNAME$BUNDLE_NAMEController;

use SymfonyBundleFrameworkBundleControllerController;
use FOSRestBundleControllerAnnotationsView;

class UsersController extends Controller
{
public function getUsersAction()
{
$users = $this->getDoctrine()->getRepository('$USERNAME$BUNDLE_NAME:User')
->findAll();
return array('users' => $users);
}
}

Test Its Working

Run the following command to check that all of your routes/configurations are set up correctly with the following command:
../../../app/console router:debug
You should see output similar to below:

That concludes the first part of the tutorial. I will add a link to the second part as it becomes available.

References

  • Starting with REST API and Symfony

download file now

Popular posts from this blog

Tokyo Ghoul Season 1 BD Subtitle Indonesia

Tokyo Ghoul Season 1 BD Subtitle Indonesia Tokyo Ghoul Season 1 BD Subtitle Indonesia Type: BD Series Episode: 12 Status: Completed Genres: Action, Mystery, Drama, Horror, Supernatural, Psychological, Seinen Skor : 8.10 (http://myanimelist.net/anime/22319/Tokyo_Ghoul) Tahun Rilis : 2014 Subtitle : Indonesia Credit : http://anime-bd.com/ Deskripsi: Ketegangan horor yang berada di kota Tokyo dihantui oleh hantu misterius yang memakan manusia. Orang-orang dicekam rasa takut hantu ini yang identitasnya disembunyikan. Seorang mahasiswa biasa bernama Kaneki bertemu ceweknya yang bernama Rize, seorang gadis yang merupakan pembaca  novel seperti dia, di kafe dia sering berjumpa denganya. Perlahan dia kemudian menyadari bahwa nasibnya akan berubah dalam semalam setelah bertemu Rize. Link download 720p & 480p: ===================================================== ========= Resolusi 720p: Tusfiles: Ani-BD_Tokyo_Ghoul_BD_ED01_animesave.mkv � 11.5 MB Ani-BD_Tokyo_Ghoul_BD_ED02_animesave.m...

TOP TEN MOST POPULAR UNIVERSITY in Indonesia

TOP TEN MOST POPULAR UNIVERSITY in Indonesia Top ten most popular University in Indonesia based on METRO TV. the top ten most favourite University in Indonesia were taken from MetroTv. ITB Bandung => Institut Teknologi Bandung is the most favourite university which is elected by the most voters Universitas Indonesia => claimed to be the most advanced university in Indonesia.it has lots of Network as so many people graduated from UI. UGM => Universitas Gajah mada (UGM) is the oldest University (after the declaration of independence).it has 18 Fakulty (and 1 PascaSarjana).this university was the merger from others. Institut Teknologi Sepuluh November => built in 1957,ITS or Institut Teknologi Sepuluh Nopember now specialized in the technology about boat and Information Technology. Universitas Padjajaran (Unpad) => I got no Information about this university and Im sleepy atm. hehehe... Universitas Brawijaya => often called as UB / UNIBRAW, this univer...

Tarzan

Tarzan Tarzan Action Game (PC/Full/Eng) Game Platforme(s) : PC | Language : English | Release Date : Feb 16, 1999 Publisher & Developer : Disney Interactive | Genre : Action/Adventure | Size : 38 Mb Tarzan Action GameSummer. The days are hot and long, and its time for bar-b-ques, camping, and baseball. Summer doesnt just happen outside, though. Its also blockbuster movie season, when theaters screen entertainment thats typically a little lighter in content and more technically dazzling than the award-oriented films shown in the colder, darker, shorter days of fall and winter. Accordingly, summer big-screen fun has come to belong to Disney, which releases an animated feature every year to coincide with the conditions that make it easy to spend an afternoon in an air conditioned movie house, often time and time again to see the same feature over and over. If youve spent any time near fast-food franchises or a department store, then you know from all the merchandise that this years ...