Setup RESTful API in Yii2

In this article, I will show you how to setup RESTful API in Yii2 framework. It is a little bit tricky because Yii2 is still in beta release (when this article is written) so the documentation is not complete enough. But don’t worry, this article will give you insight how to setup API in Yii2.

Install Yii2 Application

Our first step of course is to install Yii2 application. I will use Yii2 advanced template. Anyway, you need to install Composer first. You may install it by following the instructions at getcomposer.org After you install it, go to your htdocs or www folder. Then execute the following command to install Yii2 advanced template.

php composer.phar create-project --prefer-dist --stability=dev yiisoft/yii2-app-advanced yii2-advanced-api

or you can just use composer

composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-advanced yii2-advanced-api

This command will create a new folder named yii2-advanced-api.

Init Configuration

After you install the application, you have to follow the following steps to initialize the installed application. I copy these steps from Yii2 Getting Started

  1. Run command init (windows) or php ./init (mac/linux) to initialize the application with a specific environment.
  2. Create a new database and adjust the components['db'] configuration in common/config/main-local.php accordingly.
  3. Apply migrations with console command yii migrate. This will create tables needed for the application to work.

Yii migrate command will create table user in database automatically.

Create API folder

Inside advanced folder, you will see backend and frontend folder but we are not going to touch these folders. Yeah, we will create a new one. Let’s create a new folder called api. So, you will have api folder at same level with backend and frontend. The api folder has structure like below.

api
-- common
------ controllers
------ models
-- config
-- modules
------ v1
---------- controllers
---------- models
-- runtime
-- tests
-- web

There is v1 folder inside modules. It means API version 1. This structure allow us to support API versioning. It is possible in future to have new API version such as V2 or V3. You may take a look at my github https://github.com/deerawan/yii2-advanced-api for complete reference.

Create Country Table

Our next step is to create country table and populate country data. Here is sample country data.

CREATE TABLE `country` (
  `code` CHAR(2) NOT NULL PRIMARY KEY,
  `name` CHAR(52) NOT NULL,
  `population` INT(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `Country` VALUES ('AU','Australia',18886000);
INSERT INTO `Country` VALUES ('BR','Brazil',170115000);
INSERT INTO `Country` VALUES ('CA','Canada',1147000);
INSERT INTO `Country` VALUES ('CN','China',1277558000);
INSERT INTO `Country` VALUES ('DE','Germany',82164700);
INSERT INTO `Country` VALUES ('FR','France',59225700);
INSERT INTO `Country` VALUES ('GB','United Kingdom',59623400);
INSERT INTO `Country` VALUES ('IN','India',1013662000);
INSERT INTO `Country` VALUES ('RU','Russia',146934000);
INSERT INTO `Country` VALUES ('US','United States',278357000);

Create Country Model

Let’s create our country model. We will create it inside api/modules/v1/models.

<?php 

namespace api\modules\v1\models;

use \yii\db\ActiveRecord;
/**
 * Country Model
 *
 * @author Budi Irawan <deerawan@gmail.com>
 */
class Country extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'country';
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey()
    {
        return ['code'];
    }

    /**
     * Define rules for validation
     */
    public function rules()
    {
        return [
            [['code', 'name', 'population'], 'required']
        ];
    }
}

We need to redefine primary key using primaryKey() function because we don’t use integer auto increment as primary key. And rules() function is also needed to let Yii know what fields exist on your table.

Create Country Controller

Now we are going to create our first API controller. In order to use API CRUD generators, you only need to extend ActiveController class and specify the model class. Create the class inside api/modules/v1/controllers

<?php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;

/**
 * Country Controller API
 *
 * @author Budi Irawan <deerawan@gmail.com>
 */
class CountryController extends ActiveController
{
    public $modelClass = 'api\modules\v1\models\Country';
}

With just this little effort, your country API include

  • GET /countries: list all countries
  • HEAD /countries: show the overview information of country listing
  • POST /countries: create a new country
  • GET /countries/AU: return the details of the country AU
  • HEAD /countries/AU: show the overview information of country AU
  • PATCH /countries/AU: update the country AU
  • PUT /countries/AU: update the country AU
  • DELETE /countries/AU: delete the country AU
  • OPTIONS /countries: show the supported verbs regarding endpoint /countries
  • OPTIONS /countries/AU: show the supported verbs regarding endpoint /countries/AU.

Add Modules and API Rule

Model done and controller done, next we are going to add config for v1 modules and create API rule. Go to api/config/main.php. Add v1 modules and also rules.

<?php

$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-api',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'modules' => [
        'v1' => [
            'basePath' => '@app/modules/v1',
            'class' => 'api\modules\v1\Module'   // here is our v1 modules
        ]
    ],
    'components' => [
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => false,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'v1/country'   // our country api rule,
                    'tokens' => [
                        '{id}' => '<id:\\w+>'
                    ]
                ]
            ],
        ]
    ],
    'params' => $params,
];

We define v1 modules here and we also use Yii2 restful rule and set the controller to our country controller. We also redefine all routes to match our current id (primary key) as string (\w+) inside tokens parameter.

Add API Alias

Open common/config/aliases.php and add api alias line like the following

Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api'); // add api alias

Test API

Let’s try our country API. We will going to use POSTMAN for testing.

Test GET /countries

We are going to get all countries.

postman-post-get-all

Test GET /countries/:id

We are going to get country information with code ID

postman-post-get

Test POST /Countries

We are going to create a new country

postman-post-create

Test PATCH /Countries/:id

We are going to modify existing country information. Make sure you set it as x-www-form-urlencoded. You can also switch it using PUT.

postman-post-patch

Test DELETE /countries/:id

We are going to delete a country

postman-post-delete

Summary

Congratulations, you just successfully setup RESTful API in Yii2 framework. Go to the Github Repo

Changelog

  • Fix typo in path api config (28-nov-2015)
  • Add primaryKey function for country model (5-nov-2014)
  • Add url route handling for string (5-nov-2014)
  • Add postman example for testing (5-nov-2014)
  • Add Rule function for Country model (30-Oct-2014)
  • Remove .gitignore in Github to allow commit *.local files (29-Oct-2014)
  • cheng liang xu

    thanks It’s very helpful!
    when create api folder It does’t have quickly function must be one bye one create child folder?

    • Budi Irawan

      Yes, you need to create the folder one by one :p There is no shortcut for it AFAIK. :)

    • deerawan

      Yes, you need to create the folder one by one but if you lazy just download zip from https://github.com/deerawan/yii2-advanced-api

  • Jan-Philipp ‘Thefly’ Reining

    Thank a lot, I got stuck with the official howto/docs, your’s fixed my problems, thanks!
    (Hat trouble get the module/versioning stuff running)

    • deerawan

      you are welcome, glad to help :)

  • Bayu Hadi

    artikle yang bagus mas, boleh nanya sesuatu ngga?
    untuk extrafields() struktur active recordnya seperti apa ya?
    saya coba tambah parameter “expand” ga muncul

  • Guest

    楼主你好 刚接触yii 为什么我把你的代码下载下来在本地访问却报404? The requested URL /yii2-advanced-api/api/web/v1/countries was not found on this server. 下载的地址https://github.com/deerawan/yii2-advanced-api 请给予提供解决方案 谢谢!

  • tangqiyin

    楼主你好 刚接触yii 为什么我把你的代码下载下来在本地访问却报404? The requested URL /yii2-advanced-api/api/web/v1/countries was not found on this server. 下载的地址https://github.com/deerawan/yii2-advanced-api 请给予提供解决方案 谢谢! 我的邮箱 :517489131@qq.com

  • tangqiyin

    Hello landlord just contact Yii why I put your code download accesshas reported 404 locally? The requested URL /yii2-advanced-api/api/web/v1/countries was not found on this server. downloadhttps://github.com/deerawan/yi… Please give provide solutions tothank you! My mailbox:517489131@qq.com

    • deerawan

      I hope you can try from fresh start not from the Github. I think there are some missing files I forgot to commit to the github

      • tangqiyin

        thank you!

        Settings

        A new comment was posted on Budi Irawan

        deerawan

        I hope you can try from fresh start not from the Github. I think there are some missing files I forgot to commit to the github
        8:50 p.m., Wednesday Oct. 29

        Reply to deerawan

        deerawan’s comment is in reply to tangqiyin:

        Hello landlord just contact Yii why I put your code download accesshas reported 404 locally? The requested URL /yii2-advanced-api/api/web/v1/countries was not …
        Read more

        You’re receiving this message because you’re signed up to receive notifications about replies to tangqiyin.
        You can unsubscribe from emails about replies to tangqiyin by replying to this email with “unsubscribe” or reduce the rate with which these emails are sent by adjusting your notification settings.

  • Mu Sa

    thank you,
    can you help me with this problem:
    – before i empty the .htaccess file:
    i got the 500 error. Internal Server Error
    – after that:
    i got the 404 error, the requested URL /yii2-advanced-api/api/web/v1/countries was not found on this server.

    • Guest

      sorry everything is OK
      thank you again!

      • deerawan

        OK you are welcome :)

    • Максим Пешков

      How did you solve the problem? I have the same issue.. 404 error

      • Mu Sa

        By apply rewrite_module and add .htaccess file:
        1) LoadModule rewrite_module modules/mod_rewrite.so in httpd.conf file

        2) add yourproject/api/web/.htaccess file with this content:
        RewriteEngine On
        # If a directory or a file exists, use the request directly
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        # Otherwise forward the request to index.php
        RewriteRule . index.php

  • How I send post param in POST, PUT, DELETE …, I try x-www-form-urlencoded, from-data, json but not work.

  • Mohammad Shahid

    Why it is plural name in the url “countries” while controller name is “Country” ? I am creating a new table “city” and created controller and model files in the same way but it is not working. Is there anywhere url configurations are done?

    • deerawan

      The single or plural names of REST has became a debate for decade. Some people prefer to use plural names for REST. Here is one good article you can read about REST http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

      • Mohammad Shahid

        thanks :) got it.

    • deerawan

      Have you added the controller to api/common/config/main.php ?

    • 李慧斌

      Add this setting

  • Andy

    Hi! Nice REST example. GET works but did you test POST to add a new country?
    POSTing the following JSON
    {
    “code”: “AA”,
    “name”: “AAAA”,
    “population”: 1
    }

    to http://localhost/yii2-advanced-api/api/web/v1/countries

    causes an error:

    Field ‘name’ doesn’t have a default valuenThe SQL being executed was: INSERT INTO `country` (`code`) VALUES (NULL)”,

    Yii seems not to be able to assign the JSON-values to the corresponding fields…

    Do you know how to get this working?!

    • deerawan

      I recommend you to use POSTMAN (search it on chrome webstore) and set to x-www-form-urlencoded with POST type.

      • Mohammad Shahid

        Hi.. I am also facing the same issue, I’m using postman and and tried all combination to post values, but getting same error as Andy is getting, I tried form-data and x-www-form-urlencoded both, but not able to post values.

        • deerawan

          Hi, please update the country model class, I forgot to commit function rules() there.

          • Mohammad Shahid

            Yeyyy… I pulled latest code and its working fine.. thanks a ton :)

          • deerawan

            You are welcome, brother. Glad can help. Happy coding!

          • Andy

            Thanks! Now it works after adding rules()!!!

            JSON works if you add the header ‘Content-Type = application/json’ in postman and
            add the following request to main.php > ‘components’ => definition:

            ‘components’ => [
            ‘request’ => [
            ‘class’ => ‘yiiwebRequest’,
            ‘parsers’ => [
            ‘application/json’ => ‘yiiwebJsonParser’
            ]
            ],

            => https://github.com/yiisoft/yii2/issues/4198

  • Mohammad Shahid

    Is there any new post coming on “how to use basic user authentication using rest yii2″ including these details?
    1) send username/password from login page to get access token
    2) send back access token to authenticate it and get data if access token is valid

    • deerawan

      Maybe, hehe. I’m quite busy these days. But this is really interesting topic. There are some articles out there that explain about rest authentication generally.

  • Mitesh Chavda

    Thanks for this wonderful work.

    I have read doc 2.0 for rest api and followed same steps but couldn’t get success. But you have done pretty easy way. My question is why you have created separate api folder? can you i do the same in front end folder? It would be great if you give more info.

    • deerawan

      Hi Mitesh :) In my scenario, I assumed frontend is used as main website which visitor see. Backend is for admin page. I want separate folder for api to be more maintainable later. But you can use frontend folder if you want. No restriction :)

  • Mohammad Shahid

    Is there any way to sort the data like GET /countries?sort=name asc ?

  • k1288

    I spend all day trying to figure out why I kept getting 404 not found and finally figured out. The recent apache version from 2.3.0 up have AllowOverride NONE by default instead of AllowOverride All. “.htaccess” dose nothing because of AllowOverride is set to None

  • Максим Пешков

    Thank you for this tutorial!! Very usefull!

  • azlarsin

    Hi,buddy.

    thanks for your code, it`s worked on my page.

    i have configured my “apiconfigmain.php” like this:

    ‘errorHandler’ => [

    ‘errorAction’ => ‘site/error’,

    ],

    ‘urlManager’ => [

    ‘enablePrettyUrl’ => true,

    ‘enableStrictParsing’ => true,

    ‘showScriptName’ => false,

    ‘rules’ => [

    [

    ‘class’ => ‘yiirestUrlRule’,

    ‘controller’ => ‘source’,

    ‘only’ => [‘view’],

    ],

    ],

    ],

    ],

    sorry for my bad layout!

    i have an error in the route, in my web, the route has changed as ‘localhost/api/countries’, but it report an error of 404.

    only i set ‘enableStrictParsing’ as false and ‘showScriptName’ as true, it will work with ‘localhost/index.php/api/countries’…

    if it worked only by modules?

    • deerawan

      Have you set your .htaccess to support this rewrite URL?

      • azlarsin

        Hi, thank you. It is indeed that file.
        Thanks again!

  • arunrajginfo

    Still it showing 404 (Not Found) error.

    checked my htaccess file :

    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule . index.php

    i have checked :

    http://localhost/advanced-api/frontend/web/ and
    http://localhost/advanced-api/backend/web/

    It’s working

    but

    http://localhost/advanced-api/api/web/ – Not working

    • deerawan

      Are you using Apache? If yes, how about the AllowOverride? Have you set it into “All” ?

  • Elumar khaled

    Hi, I have tried to setup REST API in yii2 basic application using the guide 2.0 ( http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html ) but still i am facing error 404 even i follow step by step the guide and update the config.php as per the document,any advise ,thank you in advance.

  • Rambo

    I will never told you that we even can’t use the postman-rest-client-packa because the GFW,hehe

  • napo

    Hi guys…

  • Aris Moratalla

    Very nice tutorial! I am already using the API on my project. I have three tables, Request, Sample, and Test with the following relations: Request has many Samples and Samples has many Tests. When retrieving a Request (through the url http://localhost/yii2-api/api/web/v1/requests?expand=samples), I am able to also attach the Samples data in the response.

    How would I be able to include the Tests data when retrieving the same Request.Is there a way I can also use “expand” on Samples in the url?

    Thanks and more power!

  • Nakarin Kongsumrit

    Due to your latest github,I think “Go to api/common/config/main.php. Add v1 modules and also rules.”
    should be
    “Go to api/config/main.php. Add v1 modules and also rules.”.Maybe I miss something,very good article indeed.Thx.

  • Thank you for this tutorial!

  • Leandro Salas

    Hi Budi, thank you for the tutorial really helpful.

    I got all working really good as you wrote in this guide, but I need to send the country info as JSON in the body when I do the POST or PUT I can’t use parameters as you are doing. I need to send the raw JSON in the body request, I don’t have any idea of how it works I tried many thing but anything worked.

    So please!, if you know how to accomplish this approach it can really help me a lot.

    bellow in the picture you can see what I am trying to do, I am sending that JSON and it’s apparently working but it doesn’t store any of the fields that I sent.

    Thank you.

  • oziknow

    sangat menarik dan sudah saya coba

    tapi masih bingung seting data json nya

    bagiamana kalomada 2 tabel atau lebih , misalkan post dan kategory
    bagaimana biar data json yang muncul langsung isi berita, dan nama kategorinya langsung bukan fk nya kategory

    apakah diseting di model dalam folder v1, atau bagaimana?

    maaf baru belajar mas.

  • chizuoka

    Hi.. May I know why your github.com codes do not have the api/common/ folder… Instead seems all the example codes are in the modules folder.

    I just extracted the files from github to my server and I get a page not found error at /api/web/v1/countries.

    Putting a simple html page in that folder opens correctly.

    Am I doing it right or am I missing something?

    Thanks

  • Adrián Apodaca

    Hi. First of all thanks for the tutorial.

    I can’t make it work… I’ve try in a lot of ways, with my proyect, creating new one, using the code of github and in all cases I’m getting error 500 when I try in POSTMAN.

    I’ve check the configuration and front and backend is working fine with enablePrettyUrl = true and .htaccess, but when I try api/web/v1/countries allways get error 500…

    What I’m doing wrong? I’m a little desesperated…

  • Daniel

    I tried nearly everything but did not get it working.
    When I use my .htaccess file like described here I get the error 500 when I delete it I get 404.
    I enabled “AllowOverride All” in MAMP and it is working for my other app.

    The folder structure is like
    my_app
    -frontend (here it is working and i can use REST)
    -api (here I get 500)

    What else can I try?

  • method PATCH,DELETE error 405 {
    “name”: “Method Not Allowed”,
    “message”: “Method Not Allowed. This url can only handle the following request methods: GET, HEAD.”,
    “code”: 0,
    “status”: 405,
    “type”: “yii\web\MethodNotAllowedHttpException”}

  • Lau Le

    Great !
    The title is very well.But when i use GET with url …/v1/countries?name=Brazil, the result is returned all data in Country table, not only “?name=Brazil”.
    I don’t know where am i wrong ?
    Anyone may help me this ? Thanks.

  • nick

    thanx it’s really helpful, i will pass it on thanx buddy

  • Wout Provost

    Thank you for this helpful tutorial, although as a beginner, I had to figure out a few things myself. And having read the comments below, a few other people have (had) similar problems.

    – Make sure to enable “rewrite_module” in the httpd.conf file located in the apache folder of you webserver. By enable I mean uncomment “LoadModule rewrite_module modules/mod_rewrite.so”. That is removing the “#” at the front if it is present. Otherwise, a request to the webpage will throw errorcode 500.

    – Make sure to have “AllowOverride” on “all”, in the same file. Otherwise, a request to the webpage will throw errorcode 404.

    – Restart Apache after these changes, to let them take effect.

    – The common folder isn’t used in the github example, the files “Country.php” and “CountryController.php” are moved to the “modules/v1/models” and “modules/v1/controllers” folders respectively.

    At last their are a few extra files, not mentioned in this tutorial, but present in the github example that you need to create:

    – api/web/.htaccess
    – api/web/index.php
    – api/modules/v1/Module.php
    – api/config/main-local.php
    – api/config/params-local.php
    – api/config/params.php

    I have uploaded a working example (for some reason the github example didn’t work for me) here. Make sure to create a database with a country table as described in the tutorial and change the databasename in “common/config/main-local.php” if you try it out.

    • Wout Provost
      • Freddy Dhalier Colmenares

        Thanks a lot Wout Provost but I have some questions. Maybe you could help me. Your version works for me perfect in a project from 0 but when I’m trying in the same server in an other project I only get 404. I’m making simple just copying the API’s folder inside of the project and testing with postman but it’s lost time, that shouldn’t work?

        • Wout Provost

          Just copying the API folder in another project won’t work. I don’t know what problem you could have with the info you’ve given, but just makes sure you’ve done all of the following:
          – Make sure you create an alias for the API folder in ‘common/config/aliases.php’, as described in the tutorial above.
          – Make sure the database configuration and authorization is correct in ‘common/config/main-local.php’ under ‘components[‘db’] (host, dbname, username, password).
          – Make sure you have an actual database with a name equal to ‘dbname’ from the previous point.
          – The model in the API folder expects a table in the database named ‘country’ with attributes ‘code’, ‘name’ and ‘population’. Primary key is ‘code’.

          • Sorry for not explaining all that but I already did those steps. The problem is that I always get 404 in the project like if the .htaccess wasn’t there. if you want to try in postman this is the URL: http://yattsiapp.com/yattsi/api/web/v1/countries all the API’s folder have the same content as you published. This is the URL that works: http://yattsiapp.com/yii2-advanced-api/api/web/v1/countries

          • Wout Provost

            I suppose you’re trying to write a controller and model that don’t use the ‘yiirestActiveController’ and ‘yiidbActiveRecord’ classes but the ‘yiirestController’ and ‘yiibaseModel’ classes instead? If so, I unfortunately haven’t had the opportunity to expand my project beyond the steps provided in the above tutorial. The only thing I can think of is that you’re not using ‘v1′ in one of your links. I suggest you take a look at the documentation provided for RESTful Web Services at http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html. Please let me know when you’ve found a solution.

          • Nilesh Chhadawelkar

            Hi Wout

            I facing below error when I run your application. Please suggest solution for the error. Error attached.

            Thanks
            Nilesh

          • deerawan

            Hi Nilesh,

            You need to create a folder named “assets” inside advancedAPI/api/web/

            The error said so

          • Henrey Yash

            .htaccess is playing exceptionally imp role in here… as routing.. u need to have it..

            i understood it after wasting an entire day… i faced it today.. :D

    • Henrey Yash

      Hey Wout.. thanks for the point to point description… i had all the things similar but only .htaccess file wasnt there and due to this i wasnt getting the response. looks like .htaccess’s rewrite mod played an imp role

  • Kshitiz Singh

    Suppose,
    I have one custom action in my module controller say actionCategory() in a new controller called TestController.

    I am trying to implement this https://github.com/sirinibin/yii2rest

    I am able to call actionIndex but not above when i run
    http://localhost/modulename/test WORKING
    http://localhost/modulename/test/category NOT WORKING

    How do i call this in rest api?
    Is there any config i have to add?
    Any help will be appreciated.

  • Alex Li

    I’m bit confused such moment: why we call cointrIES in url, but our Controller name has Country ? How it works ?

    • deerawan

      This is the most used convention in RESTful API to using plural in URL and Yii follows this rule. So, country become countries, user become users. Yii automatically handle this.

      • Alex Li

        Thanks for your answer, Can you help in one more question: We call our api such URL: api/web/v1/countries, what and where should I change to call it like this: v1/countries, without leading api.web ? I tried to change extraPatterns in rules, but it didn’t help me

        • deerawan

          Alex, you need to create virtual host for this. Take a look at this tutorial http://jason.pureconcepts.net/2014/11/configure-apache-virtualhost-mac-os-x/. Then you need to specify the DocumentRoot to your-path/api/web then you can use your domain (example: myapi.local/v1/countries)

          • sandeep

            how can i use actionIndex ,actionCreate,etc ..please give the urlmanager formate ….

            how i write the url in urlmanager

            [

            ‘class’ => ‘yiirestUrlRule’,

            ‘controller’ => ‘v1/user’,

            // ‘HEAD users’ => ‘user/index’,

            ‘tokens’ => [

            ‘{id}’ => ”,

            ‘HEAD users’ => ‘user/index’,

            ]

            ]

            this is not hitting action

  • Philipp Frenzel

    Hi, I’m trying to pass over a variable to the index action which should work like a scope to the data returned… sadly I can’t figure out, how to pass over the parameter to the action… I tried with the prepareDataProvider function, but I don’t get it up and running :(

  • sevikon

    How can I remove /web/v1 from url -> I woulid like to access api/web/v1/countries on api/countries.
    I will be grateful for any help you can provide.

    • Budi Irawan

      Hi sevikon, you don’t need to create v1 folder to achieve this. Just create directly the controller folder outside module folder like yii2 basic app.

  • Bilal Bayasut

    how about this?

    403 Forbidden

    Forbidden
    You don’t have permission to access /latihanyii/api/web/v1/armada
    on this server.

    Apache/2.4.7 (Ubuntu) Server at localhost Port 80

    I have changed the apache2.conf allowoverride..but still..

  • Benson Wamae III

    my data comes out as xml, how do I change it to json?

    • Yonas Alemayehu

      i think this is old but i faced the same issue and solved is using the below

      at the end of your url use ?_format=json

  • harry

    I am confused here.

    controller name is “CountryController”. And no where configured url as “countries”;

    then why url request is “countries” and not “country”

    • Budi Irawan

      Hi Harry, this is restful pattern that Yii uses. It makes entity to be plural. Country become countries, student become students, etc.

  • Raymond Wijaya

    bagaimana kalau menggunakan lebih dari 1 koneksi database?

    • Budi Irawan

      bisa bro, di Yii2 ada fitur untuk switch database. Monggo ditelusuri dokumentasinya.

  • Linh Tran

    Can I help me!

    Warning: require(C:xampphtdocsyii2-advanced-api-masterapiweb/../../vendor/autoload.php): failed to open stream: No such file or directory in C:xampphtdocsyii2-advanced-api-masterapiwebindex.php on line 5

    Fatal error: require(): Failed opening required ‘C:xampphtdocsyii2-advanced-api-masterapiweb/../../vendor/autoload.php’ (include_path=’.;C:xamppphpPEAR’) in C:xampphtdocsyii2-advanced-api-masterapiwebindex.php on line 5

    • Budi Irawan

      You need to run composer install first in your terminal.

    • César Franco

      Hi! You need to update your framework library executing “comper install”.

  • Skygaz3r

    I’m overriding the CREATE method with my own action:

    public function actionCreate() {

    $params = $_REQUEST;
    if (!empty($params[“name”]) && !empty($params[“code”])) {
    $model = new $this->modelClass;
    foreach ($params as $key => $value) {
    if (!$model->hasAttribute($key)) {
    throw new yiiwebHttpException(400, ‘Invalid attribute:’ . $key);
    }
    }

    $model->attributes=$params;
    try {
    $model->save();
    } catch (CDbException $ex) {
    // … NEVER REACH THIS POINT :-(
    throw new yiiwebHttpException(405, ‘Error saving model’);
    } catch (Exception $ex) {
    // … NEVER REACH THIS POINT :-(
    throw new yiiwebHttpException(405, ‘Error saving model’);
    }

    } else {
    throw new yiiwebHttpException(400, ‘No data input’);
    }

    }

    The problem is when the model is trying to be saved, in my case there is an “Integrity constraint violation” in my database.

    What I would like is to handle that error and run my “catch”, but I don’t know how to “catch” that error, because Yii is “taking control” of that error and throw a 500 error as response.

    How can I handle the “model save” errors ?

    And other questions … is that the way to “override” the standard actions to handle data in a custom way ?

    That’s the way I saw to do it for CREATE method, and I saw this for INDEX method (http://stackoverflow.com/questions/23474106/how-to-select-and-return-data-using-fks-in-yii2-restful-api) … the “country” example here is “too basic”, I would like more documentation to handle custom operations in each method, how to handle the model, attributes, save, queries …

    thank you

  • Stephen Embree

    When I attempted to enable Basic auth for this API, I was seeing “Class common/models/User not found” errors. I discovered that I needed to add the following line to api/web/index.php to make it work: require(__DIR__ . ‘/../../common/config/bootstrap.php’);

    • esiaz

      thanks for sharing!

    • Mahesh S

      Thanks for this share. It really helped!

  • Piter Novian

    if use localhost all working properly, but if use public use domain URL ERROR
    example : http://www.domain.co.id/v1/countries

    “The requested URL /v1/countries was not found on this server.”

  • Moawia

    getting page 404 on nginx for:

    http://vp2.dev/api/web/v1/countries
    http://vp2.dev/api/web/v1/country
    http://vp2.dev/v1/countries

    the route should be site.com/v1/countries … right?

    what the error?

  • dantart

    I have tried to create a UserController.php in the api/modules/v1/controllers folder, and there put this

    public $modelClass = ‘commonmodelsUser';

    because I want to use the common model User, I don’t want to rewrite again the same User model in “api” … but it says:

    {“name”:”PHP Fatal Error”,”message”:”Class ‘common\models\User’ not found”,”code”:1,”type”:”yii\base\ErrorException”

    help, please ;-)

    • Budi Irawan

      Hi dantart,

      Actually, it can use model from common folder. Btw, Why there is no forward slashes on $modelClass value?

  • Piter Novian

    extrafields, semoga membantu mas bro.

  • César Franco

    It would be a good idea to update the route “api/common/config/main.php” of the section “Add Modules and API Rule” to “api/config/main.php” to avoid confusion. Greetings.

    • Budi Irawan

      Ah yes, it was a mistake. I updated it. thanks Cesar

  • César Franco

    I have a question… why do we get a JSON format if we didn’t configure the JSON format which is showed in http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html? Thanks in advance.

  • Vikram

    Following this I am unable to use Gii generator, it loads but on clicking preview I am getting “Namespace must be associated with an existing directory.” error message. Is there anything we need to configure to use Gii.

  • Guntur Budi Herwanto

    Terimakasih, sangat membantu tutorial dan repo github nya..
    Saya ingin menanyakan, apakah ada tutorial yang melibatkan Autentikasi pada rest di yii2 ?

    • Budi Irawan

      Untuk di Yii2 belum pernah explore lagi sejauh ini, authentikasi paling basic bisa menggunakan token. Itu yg pernah diimplementasikan personally. :)

  • D Akhil Reddy

    how to block user from accessing all countries when coutries url is given. Instead they should only access contents when action is provided

  • johnsnails

    Missing comma on line 41 of api/config/main.php

    ‘controller’ => ‘v1/country’, // our country api rule,

  • johnsnails

    Typo, the table name is called ‘country’ but the INSERT says ‘Country’ I think the table names are case sensitive depending on the underlying OS.

  • Aaron Radich

    Great article. I’m having trouble, though, implementing the API folder with the most recent version of the advanced template, which has the _protected folder. When I try to run the web service, I am getting a ReflectionException error:

    ReflectionException
    Class apimodulesv1Module does not exist

    Here is the config for the module in config/main.php:

    ‘modules’ => [
    ‘v1′ => [
    ‘basePath’ => ‘@app/modules/v1′,
    ‘class’ => ‘apimodulesv1Module’
    ]
    ],

    Any idea what is wrong? I have my api folder directly under the root, while the advanced template has a number of the folder moved into _protected. Thanks.

    • kirill.vo

      I have the same problem. Did you find a decision?

      • Alejandro Quiroz

        Same problem. Solved changing in yii2-advanced-api/common/config/aliases.php: Yii::setAlias(‘api’, dirname(dirname(__DIR__)) . ‘/api’); // add api alias WITH PHP CODE OPEN < ? php
        Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api'); // add api alias

  • Sonu

    Great Tutorial . I have implimented the api module in my project when a error occur like controller name wrong then it directly throw me a object(yiiwebNotFoundHttpException) instead of 404 page. But in your controller when a trying to put wrong url name then it will show a 404 error page. I totally replaced the main.php and controller is also same . But don’t know which part i’m missing for the 404 error page, Please help and also in this module can i show a error exception at controller level.

  • Jnanendra Veer

    How to configure rest api in yii2 basic.

  • KP

    can we create generic controller for all model classes?

  • Devmnnit

    Hi, I am able to create rest api but it returns response in xml format. I want the response in json format, i have tried many solution but any one is not working. I have added json request parsor in main.php file. But it is not working. Please help me to figure out this.

    • Themroc

      Try adding
      ———-
      use yiiwebResponse;

      public function behaviors() {
      return [
      [‘class’ => ‘yiifiltersContentNegotiator’, ‘formats’ => [ ‘application/json’ => Response::FORMAT_JSON ] ],
      ];
      }
      ———-
      in your controller. That just worked for me.

  • Manish

    Hi. I am new in api. I want to add project in api in my actionCreate in ProjectController.

  • Eleazar Embuscado

    How can I add a controller if I have a hudreds of controllers in my project? Iam ely newbie in YII2.0

    thanky ou for answering

  • Maxta

    For me all things worked properly but when I create new model and controller for another table according to the country example, I got 404 not found error when accessing the new model through the API

    • Maxta

      I just solve my problem. I have forget that all model got plural, so I just add “s” at the end of my model and it sorted the results. very thanks for this tutorial

  • Yasar Arafat A T

    Not working for me :( showing blank page in browser and 500 error in postman

  • Oleg Peretyatko

    Спасибо, дружище, очень помог!

  • Ebongue

    I follow all guide. and i read somme comment and adjust my project by following the indication of “Wout Provost

    ” see below.
    But i continue to get error 500. I have made more than one week on how to create RESTFUL api with YII2 and i block on error 500 or error 404.

  • Giovanny Franco Herrera

    Hi.
    Thanks for the tuto, it is great.

  • kaseybackman232

    Thank you for perhaps the most level headed thing I have read today. I think it could also be useful for everyone to know how and where to filla form online. BTW, there is an online service through which you can fill out a IRS SS-4, the fillable blank is here http://goo.gl/3kg7pG.

  • Bicsák József

    Thanks for this post. It works fine, but I have one problem:

    The PUT http request answers “405 Method not allowed”
    Allow →GET, POST, HEAD, OPTIONS

    This is an apache issue?
    Apache/2.4.7 (Ubuntu 14.04)
    How can I fix it?

    • Jozsef Bicsak

      Problem solved, in .htaccess:

      RewriteCond %{REQUEST_METHOD} (PUT|POST|GET|DELETE)

      RewriteRule . index.php

      order deny,allow
      allow from all

  • rashedhsn

    Thank you very much for your nice tutorial. But I have a question how can i provide security of my API? In this system anyone know the URL they can easily do anything of my system. Do you have any more tutorial for API security?

  • tiến Vũ Văn

    thank you for this tutorial, i’m beginner. although, my project has working but i had a problem:Get method only get 20 records ? how to config functions: view, add, update… in yii2 because i just seen “public $modelClass = ‘apimodulesv1modelsCategory'; ” in controller and function tableName, rule,primaryKey in model so why it’s work ??
    please for me a explain! thanks so much!

  • abhishek sharma

    i use this example but show error 404 on this url http://localhost/yii2-adv-rest/api/web/
    here my project name is yii2-adv-rest

  • Ade Mahendra

    Halo Mas Budi, saya mau tanya, setiap kali saya post data berupa web url itu kenapa selalu error 403 ya,
    misal saya post pada text “http://www.example.com/” ini selalu forbidden.
    kira2 itu kenapa ya>

  • Taslim Waris

    Hi,
    I donwload the code form https://github.com/deerawan/yii2-advanced-api :
    I am running this url http://localhost/yii2-advanced-api-master/api/web/v1/countries on POST MAN .
    This gives error::

    Warning: require(D:xampphtdocsyii2-advanced-api-masterapiweb/../../vendor/autoload.php): failed to open stream: No such file or directory in
    D:xampphtdocsyii2-advanced-api-masterapiwebindex.php on line
    5

    Fatal error: require(): Failed opening required ‘D:xampphtdocsyii2-advanced-api-masterapiweb/../../vendor/autoload.php’ (include_path=’D:xamppphpPEAR’) in
    D:xampphtdocsyii2-advanced-api-masterapiwebindex.php on line
    5

    Can anybody tell me about seeting of file and db.
    Thanks