Cs Cart – Api support for multipart form-data

Published On: 16 September 2015.By .
  • Digital Engineering

Cscart 4+ has one great feature i.e API. There are some basic apis already written in cscart, like Products, Orders, Users etc. You can check these apis in detail here http://docs.cs-cart.com/4.1.x/api/index.html. Currently, Api’s in Cscart has only support for content type application/json and text.

Now suppose we are building a mobile app for our Web store and we need to upload product images from mobile app. But our api only support application/json format. If we are strict with current scenario then we need to send image content as binary format or base64 encoded format, which increase our request size which is not a good solution. We can also send Image path from any live store as cscart supports image upload from url and no need to change anything.

Best way to upload images is add support for content type multipart/form-data and modify or overwrite Product api . For that we need to understand existing api system. How request is processed and how response is generated.

What happen when any api request is initiated?

Api class constructor has format parameter which is a array of format it supports. And default value is array(‘json’, ‘text’). When cscart create a object of Api() class it pass nothing as parameter so default value is passed.So we have to change that by rewriting fn_init_api().

To recreate Api object we create our addon and in his init.php write this code

Now we have fordata format for our request. We have to bind that format with multipart/form-data request. For that create a file at /app/Tygh/Api/Formats/Formdata.php and copy following code.

Now we have done with format. We add parser for request with content-type multipart/form-data. We just need to do is upload our image.
For that we need to create a version for our product api. Create a folder structure like this in our addon Tygh/Api/Entities/v30. Create file Products.php in this folder with following code.

That’s it. Now we can use this api by this url http://domainname.com/api/3.0/products.

Related content

That’s all for this blog