Create a Custom API in OpenCart

Create a Custom API in OpenCart

You’ll need to create custom APIs for unique requirements in your project development at some point in time, and that’s what we’ll cover throughout the course of this tutorial. In our custom API module, we’ll fetch the list of all products available in the store, and it’ll be a JSON encoded output as required by the REST standards in OpenCart.

I assume that you’re familiar with the basic module development process in OpenCart.  Another important point: I’m using the latest version of OpenCart, that is as of writing this, and you should do that too to ensure the compatibility of core APIs.

Without wasting much of your time, I’ll straight away dive into the practical stuff, and that’s what the next section is all about.

A Glance at the File Setup

Let’s have a look at the list of files required for the desired setup.

  • catalog/controller/api/custom.php: It’s a controller file, and most of our application logic resides in this file.
  • catalog/language/en-gb/api/custom.php: It’s a language file that holds language variables.
  • common.php: This file holds the common code for reusability purposes.
  • login.php: It’s a file that demonstrates how to log in to the store using the REST API.
  • products.php: It’s a file that demonstrates how to fetch products using our custom API module.

So, that’s all it takes to set up our custom API module and test it using PHP CURL library.

We’ll start with the controller file, go ahead and create a file catalog/controller/api/custom.php with the following contents.

// catalog/controller/api/custom.php
class ControllerApiCustom extends Controller {
public function products() {
$json = array();

if (!isset($this->session->data[‘api_id’])) {
$json[‘error’][‘warning’] = $this->language->get(‘error_permission’);
} else {
// load model

// get products
$products = $this->model_catalog_product->getProducts();
$json[‘success’][‘products’] = $products;

if (isset($this->request->server[‘HTTP_ORIGIN’])) {
$this->response->addHeader(‘Access-Control-Allow-Origin: ‘ . $this->request->server[‘HTTP_ORIGIN’]);
$this->response->addHeader(‘Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS’);
$this->response->addHeader(‘Access-Control-Max-Age: 1000’);
$this->response->addHeader(‘Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With’);

$this->response->addHeader(‘Content-Type: application/json’);

Probably, it should be pretty familiar stuff if you’re aware of the structure of OpenCart module files. However, we’ll discuss the important snippets from the products method.

First of all, we have to check the authenticity of the request, and it’s checked by the existence of the api_id variable in the active session. In the case of a valid and authenticated request, we’ll go ahead and fetch all the products using the getProducts method of the core Product model. Of course, it’ll give a permission denied error message in the case of invalid login.

Next, there’s a generic security check to protect against CSRF attacks. It’s accomplished by checking the existence of the HTTP_ORIGIN variable, and adding appropriate headers if it does exist.

Finally, we’ve used the json_encode function to encode the $products array, and the result is passed as an argument of the setOutput method.

Next, we’ll go ahead and create a language file for our module at catalog/language/en-gb/api/custom.php with the following contents.

// catalog/language/english/api/custom.php
// Error
$_[‘error_permission’] = ‘Warning: You do not have permission to access the API!’;

So, that’s it as far as the OpenCart-related file setup is concerned. From the next section onwards, we’ll create the files that help us test our custom API using the PHP CURL library.

How It Works

Before we go ahead and test our custom API module, you should make sure that you’ve created API user credentials from the back-end of OpenCart.

If you haven’t done so yet, it’s pretty easy. Head over to the back-end, navigate to System > Users > API, and add a new API user. While doing so, it’s important to note that you also need to add an IP address from which you’re supposed to make API calls.

Go ahead and create a common.php file and paste the following contents in that file.

function do_curl_request($url, $params=array()) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, ‘/tmp/apicookie.txt’);
curl_setopt($ch, CURLOPT_COOKIEFILE, ‘/tmp/apicookie.txt’);

$params_string = ”;
if (is_array($params) && count($params)) {
foreach($params as $key=>$value) {
$params_string .= $key.’=’.$value.’&’;
rtrim($params_string, ‘&’);

curl_setopt($ch,CURLOPT_POST, count($params));
curl_setopt($ch,CURLOPT_POSTFIELDS, $params_string);

//execute post
$result = curl_exec($ch);

//close connection

return $result;

As you can see, it contains just one function, do_curl_request, which will make a CURL call to the URL passed by the $url argument. The second argument is an array of parameters in case you need to POST the data.

The other important things to note are the CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE settings. These set the file in which the cookies will be stored and read from. As we’ll need to make authenticated calls, it’s a must! Of course, you want to change the path /tmp/apicookie.txt according to your system settings. Make sure that it’s writable by the web server too!

Finally, the function returns the response by the CURL request!

Obviously, the first thing to do is to start the session, and you’ll need to use the login method. Let’s have a look at an example. Go ahead and create a login.php file with the following contents.

require “common.php”;

$url = ‘http://your-opencart-store-url/index.php?route=api/login’;

$fields = array(
‘username’ => ‘demouser’,
‘key’ => ‘ysvF7M1nqNYiZV3GFtU252jhn0FrCWMdH8Kw8qR6DApZ7RSJWCN7S0IvIxnti1QP2wUNsYCaG6vHa2l2q8FTFbWNwNYQUO58CfSYJHHJRG0vt7OBN60BnE5MdEVLBSSJVBZJ7ioFuiAmQN1dmBO56dmaawULlY8lnWFXQimecZznUo7NCJHp3rkL1tOAYgeIUl1oVjzrZ7cayikQEvUtwIGj7Ai4XudDH70E7hKGNJcXPiY5RfgFI8PQ8eLg1FZJ’,

$json = do_curl_request($url, $fields);

First, we’ve included the common.php file created in the previous section. Next, the $url variable defines the API login URL of the OpenCart store. Next, the $fields array holds the API user credentials created earlier.

Finally, we call the do_curl_request method to log in. Importantly, you should see a token variable in the $json object. Note down the value of that variable as we’ll need to pass it while making subsequent API calls.

Next, let’s create a products.php file with the following contents.

require “common.php”;

$url = ‘http://your-opencart-store-url/index.php?route=api/custom/products&token=GtULQW9ZMhhHLi3ooobDukIqTmqOZ1fJ’;
$json = do_curl_request($url, $fields);
$data = json_decode($json);


The important snippet to note in the above example is the route querystring variable. It’s set to the api/custom/products value, which by convention calls the products method defined in the custom.php controller file created at the beginning of this tutorial. Also, we’ve passed the token variable along with its value to make sure that we have access to the API.

Anyway, what we’re interested in is the proper JSON encoded output in the $data variable. And that’s what you should see when you run the products.php file! It should work out of the box if you’ve created proper user credentials and set up the files as explained.

This is just scratching the surface of what the REST API in OpenCart is capable of. In our case, it was a pretty simple yet effective example to demonstrate the topic. Having said that, you could extend it and implement tailor-made solutions according to your requirements.

That’s it for today’s article. Don’t hesitate to ask queries and leave your suggestions as they are valuable!


Today, we’ve discussed how you could create a custom API in OpenCart by creating a custom module. In the process, we went through the complete workflow to achieve the aforementioned functionality.

What’s the Best File System for My Linux Install?

Linux File Systems

What’s the Best File System for My Linux Install?

File systems: they’re not the most exciting things in the world, but important nonetheless. In this article we’ll go over the popular choices for file systems on Linux – what they’re about, what they can do, and who they’re for.

file system ext4

If you’ve ever installed Linux before, chances are you’ve seen the “Ext4” during installation. There’s a good reason for that: it’s the file system of choice for just about every Linux distribution available right now. Sure, there are some that choose other options, but there’s no denying that Extended 4 is the file system of choice for almost all Linux users.

What can it do?

Extended 4 has all of the goodness that you’ve come to expect from past file system iterations (Ext2/Ext3) but with enhancements. There’s a lot to dig into, but here are the best parts of what Ext4 can do for you:

  • file system journaling
  • journal checksums
  • multi-block file allocation
  • backwards compatibility support for Extended 2 and 3
  • persistent pre-allocation of free space
  • improved file system checking (over previous versions)
  • and of course, support for larger files

Who is it for?

Extended 4 is for those looking for a super-stable foundation to build upon, or for those looking for something that just works. This file system won’t snapshot your system; it doesn’t even have the greatest SSD support, but If your needs aren’t too extravagant, you’ll get along with it just fine.

file systems btrFS

The B-tree file system (also known as butterFS) is a file system for Linux developed by Oracle. It’s a new file system and is in heavy development stages. The Linux community considers it unstable to use for some. The core principle of BtrFS is based around the principle of copy-on-write. Copy on write basically means that the system has one single copy of a bit of data before the data has been written. When the data has been written, a copy of it is made.

What can it do?

Besides supporting copy-on-write, BtrFS can do many other things – so many things, in fact, that it’d take forever to list everything. Here are the most notable features: The file system supports read-only snapshots, file cloning, subvolumes, transparent compression, offline file system check, in-place conversion from ext3 and 4 to Btrfs, online defragmentation, anew has support for RAID 0, RAID 1, RAID 5, RAID 6 and RAID 10.

Who is it for?

The developers of BtrFS have promised that this file system is the next-gen replacement for other file systems out there. That much is true, though it certainly is a work in progress. There are many killer features for advanced users and basic users alike (including great performance on SSDs). This file system is for those looking to get a little bit more out of their file system and who want to try the copy-on-write way of doing things.

file systems xfs

Developed and created by Silicon Graphics, XFS is a high-end file system that specializes in speed and performance. XFS does extremely well when it comes to parallel input and output because of its focus on performance. The XFS file system can handle massive amounts of data, so much in fact that some users of XFS have close to 300+ terabytes of data.

What can it do?

XFS is a well-tested data storage file system created for high performance operations. Its features include:

  • striped allocation of RAID arrays
  • file system journaling
  • variable block sizes
  • direct I/O
  • guaranteed-rate I/O
  • snapshots
  • online defragmentation
  • online resizing

Who is it for?

XFS is for those looking for a rock-solid file solution. The file system has been around since 1993 and has only gotten better and better with time. If you have a home server and you’re perplexed on where you should go with storage, consider XFS. A lot of the features the file system comes with (like snapshots) could aid in your file storage system. It’s not just for servers, though. If you’re a more advanced user and you’re interested in a lot of what was promised in BtrFS, check out XFS. It does a lot of the same stuff and doesn’t have stability issues.

file system riser4

Reiser4, the successor to ReiserFS, is a file system created and developed by Namesys. The creation of Reiser4 was backed by the Linspire project as well as DARPA. What makes Reiser4 special is its multitude of transaction models. There isn’t one single way data can be written; instead, there are many.

What can it do?

Reiser4 has the unique ability to use different transaction models. It can use the copy-on-write model (like BtrFS), write-anywhere, journaling, and the hybrid transaction model. It has a lot of improvements upon ReiserFS, including better file system journaling via wandering logs, better support for smaller files, and faster handling of directories. Reiser4 has a lot to offer. There are a lot more features to talk about, but suffice it to say it’s a huge improvement over ReiserFS with tons of added features.

Who is it for?

Resier4 is for those looking to stretch one file system across multiple use-cases. Maybe you want to set up one machine with copy-on-write, another with write-anywhere, and another with hybrid transaction, and you don’t want to use different types of file systems to accomplish this task. Reiser4 is perfect for this type of use-case.

There are many file systems available on Linux. Each serves a unique purpose for unique users looking to solve different problems.This post focuses on the most popular choices for the platform. There is no doubt there are other choices out there for other use-cases.

What’s your favorite file system to use on Linux? Tell us why below!

The 11 Phases of a Web Developer’s Career (As Illustrated by Memes)

The career of a web developer is an interesting one with many slopes. Considering a learning curve this steep, you can fully expect to live through periods of frustration, enlightenment, self-righteousness, and every mindset in between. In this article, we’ll have some fun, by reviewing each of these phases through the lens of a meme!

Complete Noob

We all have warm feelings for the early days of our careers; the period when you have absolutely no clue what you’re doing. Like a fish out of water, each new line of code is a mystery. Doctype? Huh? What the heck does a <div> do? The first phase is an intimidating, scary, but exciting one. How many dang languages are there?


5 Best websites to make money online

Making a few quick bucks never hurt anybody. It is good to have a little side tasks going on to make some flow of greenery into your pocket. Especially as a student, we all wish to have a little side business to earn some extra allowance. To do a job in a market, to actually work out there is very tedious. To search for a part time job and to get a suitable time slot according to your schedule is very difficult. So it is better to look for other alternatives. Everyday billions of dollars are profited from the online sites and now you can earn some too. Here is a list of top 5 sites that let you make money.


How To Find Out Who’s Behind That Email Address

Picture this. You have received an email claiming that you have won some prize or amount in a lucky draw or maybe you’ve received an email that looks quite interesting. Before you can trust the message conveyed via email and before sending your reply, it’s important that you properly identify the person who is associated with this email. (more…)

Writing Your First PHP Script: Feedback Form Script


I have always believed that the most fun way to learn a new programming language, whether it is a language like C or a scripting language like PHP, is to use it to write a real-life useful program. Of course this is not the most systematic method of learning, but it works well if you already have some background in programming.