Programming With Yii2: Building a RESTful API

Final product image
What You'll Be Creating

In this Programming With Yii2 series, I'm guiding readers in use of the Yii2 Framework for PHP. You may also be interested in my Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.x.

In today's tutorial, I will review how to build a REST API in Yii to connect your application to the cloud, mobile apps, and other services. I'll guide you through Yii's REST API quick start guide and provide context and examples of common requests.

Getting Started With Yii REST APIs

Building REST APIs in Yii is actually fairly straightforward. You can leverage the existing MVC framework, but you're creating a distinct access point that you intend to be accessed by different kinds of services (not website visitors).

The Benefits of the Yii REST Framework

The Yii Framework provides broad support and detailed documentation for building APIs. Here are some of the built-in capabilities when building APIs:

  • Quick prototyping with support for common APIs for Active Record. This allows you to quickly and easily expose data model CRUD functionality via an API.
  • Response format negotiation (supporting JSON and XML by default). There's built-in support for returning data in common output formats.
  • Customizable object serialization with support for selectable output fields. It's easy to modify what data is returned.
  • Proper formatting of collection data and validation errors.
  • Support for Hypermedia As The Engine Of Application State (HATEOAS)
  • Efficient routing with proper HTTP verb check.
  • Built-in support for the OPTIONS and HEAD verbs.
  • Authentication and authorization.
  • Data caching and HTTP caching.
  • Rate limiting.

I won't have a chance to touch on all of this today.

My Interest in REST APIs

In this episode, I'll build an API to let us manipulate the Item table I created in the Twixxr service from this Twitter API tutorial. But I'm also planning to build an API for our startup tutorial series focus, Meeting Planner. A secure API will be necessary for building an iOS application for the service. The API will enable communication between the mobile app and the cloud service.

Building the REST Controller

With Yii's REST framework, we'll create an endpoint for our API and organize controllers for each type of resource.

The resources are essentially our application's data models. These extend yii\base\Model

The yii\rest\UrlRule class provides ready-made routing mapping our data model to API CRUD endpoints:

Programming Yii2 REST API UrlRule Documentation of CRUD API endpoints

Creating a Tree to Act as an API Endpoint

In the Yii2 Advanced template, there is a front-end and back-end tree, and this is extensible. To separate out the API features, we'll create a third tree to act purely as an API endpoint. 

Yii developer Alex Makarov provides this helpful guide to creating additional trees which I followed to create my third tree:

Then, I used the Atom editor to do a global find and replace of "backend" with "api" in the new api tree.

And I added the api alias to /common/config/bootstrap.php:

Configuring the URL Routing for Incoming Requests

In /api/config/main.php, we need to add the request[] to parse setup JSON parsing and the UrlRule to associate methods for the models and their endpoints:

That's basically all it takes to enable some rich API functionality for these models.

Examples With cURL

Let's begin making requests.

Requesting OPTIONS

Show me available API methods:

Here is the response (GET, POST, HEAD, OPTIONS):

GET Requests

Request: How much data is there?

Answer: 576 records across 29 pages...

Request: Show me record 15:


Request: Show me all the data on page 3:


DELETE Requests

Here's an example of a GET request followed by a DELETE request and then a follow-up failed GET attempt:

Requests for a deleted record return a 404 error.

POST Requests

For my post requests, I switched over to the Chrome Postman app:

Programming With Yii2  Chrome Directory Postman Extension Landing Page

Signing up for Postman was easy:

Programming With Yii2 Postmand Sign Up

And then I was able to submit requests to my localhost API in a more friendly GUI:

Programming With Yii2 POST Request Shown in Postman UX

Then, I retrieved the data via curl, record 577:

Postman proved essential to round out my testing as command line curl was not easy to configure for POST submissions.

Looking Ahead

In addition to its REST quickstart overview, the Yii 2.0 documentation provides detail on an array of other aspects of API creation:

I hope to have the chance to explore more of these in future episodes. But certainly, one of the next steps is to create an API for Meeting Planner in the startup series.

In closing, building a basic REST API with the Yii MVC framework is quite simple. The Yii team has done a great job standardizing functionality for a very important requirement, REST APIs. I hope you've enjoyed learning about them.

If you have any questions or suggestions, please post them in the comments. If you'd like to keep up on my future Envato Tuts+ tutorials and other series, please visit my instructor page or follow @reifman. Definitely check out my startup series and Meeting Planner.

Related Links



Related Articles