Introduction
For any successful platform, it's vital to keep up with the cutting edge features and provide them to compete in the market. Exposing APIs for your platform is one of the important features which allows integration with third-party systems, thus opening the doors to reach the larger community. Magento, being one of the most successful eCommerce platforms, provides a plethora of useful features and utilities which proves it a truly enterprise level framework.
Exposing APIs for your resources is beneficial in many ways. One of the most apparent is that it makes your resources available on different platforms, thus making them platform independent, thanks to protocols like XML-RPC/SOAP, which allows you to expose your resources in a streamlined manner. We'll use SOAP for our custom module.
In this tutorial, we'll create a custom module "Customapimodule". I assume that you're familiar with the basic module creation process in Magento. Here's a nice article explaining the basics of custom module creation.
A Glance at the File Setup
Here's the list of files required for the desired setup:
- app/etc/modules/Envato_All.xml: It's a file used to enable our custom module.
- app/code/local/Envato/Customapimodule/etc/config.xml: It's a module configuration file.
- app/code/local/Envato/Customapimodule/etc/api.xml: It's a file which declares the APIs provided by our module.
- app/code/local/Envato/Customapimodule/etc/wsdl.xml: In this file, we'll define the API methods as per the conventions of WSDL.
- app/code/local/Envato/Customapimodule/Helper/Data.php: It's a file used by theMagento translation system.
- app/code/local/Envato/Customapimodule/Model/Product/Api.php: It's a model file which implements the logic of our API methods.
- app/code/local/Envato/Customapimodule/Model/Product/Api/V2.php: It's a file to support Magento's v2 API.
Custom Module Creation: Setting Up the Files
To start with, we'll create a module enabler file. Create a file "app/etc/modules/Envato_All.xml" and paste the following contents in that file. We've used "Envato" as our module namespace and "Customapimodule" as our module name. It'll enable our "Customapimodule" module by default.
1 | <?xml version="1.0"?> |
2 | <config> |
3 | <modules> |
4 | <Envato_Customapimodule> |
5 | <active>true</active> |
6 | <codePool>local</codePool> |
7 | </Envato_Customapimodule> |
8 | </modules> |
9 | </config> |
Next, we need to create a module configuration file. Create "app/code/local/Envato/Customapimodule/etc/config.xml" and paste the following contents in that file.
1 | <?xml version="1.0"?> |
2 | <config> |
3 | <modules> |
4 | <Envato_Customapimodule> |
5 | <version>1.0</version> |
6 | </Envato_Customapimodule> |
7 | </modules> |
8 | <global> |
9 | <models> |
10 | <customapimodule> |
11 | <class>Envato_Customapimodule_Model</class> |
12 | </customapimodule> |
13 | </models> |
14 | <helpers> |
15 | <customapimodule> |
16 | <class>Envato_Customapimodule_Helper</class> |
17 | </customapimodule> |
18 | </helpers> |
19 | </global> |
20 | </config> |
Nothing fancy here—we've just declared the "Model" and "Helper" classes as per the Magento conventions.
Moving ahead, create "app/code/local/Envato/Customapimodule/etc/api.xml" and paste the following contents in that file. The "api.xml" file is used to declare the API methods exposed by your module.
1 | <?xml version="1.0"?> |
2 | <config> |
3 | <api> |
4 | <resources> |
5 | <customapimodule_product translate="title" module="customapimodule"> |
6 | <model>customapimodule/product_api</model> |
7 | <title>Demo Custommoduleapi API</title> |
8 | <acl>customapimodule/product</acl> |
9 | <methods> |
10 | <list translate="title" module="customapimodule"> |
11 | <title>List of products</title> |
12 | <method>items</method> |
13 | </list> |
14 | </methods> |
15 | </customapimodule_product> |
16 | </resources> |
17 | <resources_alias> |
18 | <product>customapimodule_product</product> |
19 | </resources_alias> |
20 | <v2> |
21 | <resources_function_prefix> |
22 | <product>customapimoduleProduct</product> |
23 | </resources_function_prefix> |
24 | </v2> |
25 | <acl> |
26 | <resources> |
27 | <customapimodule translate="title" module="customapimodule"> |
28 | <title>Products</title> |
29 | <sort_order>5</sort_order> |
30 | <product translate="title" module="customapimodule"> |
31 | <title>Product data</title> |
32 | </product> |
33 | </customapimodule> |
34 | </resources> |
35 | </acl> |
36 | </api> |
37 | </config> |
We'll start with the <resources>
tag, which wraps all the resources declared by your module. You could think of "resource" as an entity, using which you would like to categorize your API methods.
In our example, we've just declared a single resource named <customapimodule_product>
. You can name it whatever you like, as long as it's a unique identifier. Under the<customapimodule_product>
resource tag, we've declared the <model>
tag to link the Magento "Model" file, where we'll define the API method definitions. The methods for our resources are wrapped by the<methods>
tag. In our case, we've only defined a single method, "items", under the<list>
tag, which will provide a list of products.
Further, the<acl>
tag under <customapimodule_product>
is used to provide access control for our resources. The value defined in the <acl>
tag "customapimodule/product" references the definition at the bottom of the file.
At the bottom of the file, you can see that we've declared a separate <acl>
tag which defines the "customapimodule/product". In short, it's used to put our resources under access control, so that theycan be accessed by certain "API Roles" if they're defined in that way in the Magento back-end. We'll discuss this more in detail in the next part of this tutorial.
At the moment, two versions of the Magento API are supported, v1 and v2, using which you can create and expose APIs. In our example, we'll see both the methods. The <resources_alias>
tag is used to define a resource alias name by which our method will be called. We've defined it as <product>
, so whenever you want to call an API method using Magento v1 API, you will use "product" as a resource prefix. In the same way <v2>
defines a resource alias for the Magento v2 API, so the resource prefix will be "customapimoduleProduct". These things will be clearer when we see how to call our APIs in the next tutorial.
Next, let's create the "app/code/local/Envato/Customapimodule/etc/wsdl.xml" file and paste the following contents.
1 | <?xml version="1.0" encoding="UTF-8"?> |
2 | <definitions xmlns:typens="urn:{{var wsdl.name}}" xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" |
3 | xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" |
4 | name="{{var wsdl.name}}" targetNamespace="urn:{{var wsdl.name}}"> |
5 | <types> |
6 | <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Magento"> |
7 | <import namespace="http://schemas.xmlsoap.org/soap/encoding/" schemaLocation="http://schemas.xmlsoap.org/soap/encoding/" /> |
8 | <complexType name="fieldInfo"> |
9 | <sequence> |
10 | <element name="entity_id" type="xsd:string"/> |
11 | <element name="name" type="xsd:string"/> |
12 | </sequence> |
13 | </complexType> |
14 | <complexType name="fieldInfoArray"> |
15 | <complexContent> |
16 | <restriction base="soapenc:Array"> |
17 | <attribute ref="soapenc:arrayType" wsdl:arrayType="typens:fieldInfo[]" /> |
18 | </restriction> |
19 | </complexContent> |
20 | </complexType> |
21 | </schema> |
22 | </types> |
23 | <message name="customapimoduleProductListRequest"> |
24 | <part name="sessionId" type="xsd:string" /> |
25 | </message> |
26 | <message name="customapimoduleProductListResponse"> |
27 | <part name="products" type="typens:fieldInfoArray" /> |
28 | </message> |
29 | <portType name="{{var wsdl.handler}}PortType"> |
30 | <operation name="customapimoduleProductList"> |
31 | <documentation>List of products</documentation> |
32 | <input message="typens:customapimoduleProductListRequest" /> |
33 | <output message="typens:customapimoduleProductListResponse" /> |
34 | </operation> |
35 | </portType> |
36 | <binding name="{{var wsdl.handler}}Binding" type="typens:{{var wsdl.handler}}PortType"> |
37 | <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" /> |
38 | <operation name="customapimoduleProductList"> |
39 | <soap:operation soapAction="urn:{{var wsdl.handler}}Action" /> |
40 | <input> |
41 | <soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> |
42 | </input> |
43 | <output> |
44 | <soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> |
45 | </output> |
46 | </operation> |
47 | </binding> |
48 | <service name="{{var wsdl.name}}Service"> |
49 | <port name="{{var wsdl.handler}}Port" binding="typens:{{var wsdl.handler}}Binding"> |
50 | <soap:address location="{{var wsdl.url}}" /> |
51 | </port> |
52 | </service> |
53 | </definitions> |
The "wsdl.xml" file is used to define the API method definitions as per the SOAP syntax. We'll see some of the important tags in this file in the context of this tutorial.
First, we've defined the "fieldInfo" complex type, which contains two elements: "entity_id" and "name". Further, we've defined the "fieldInfoArray" complex type, which is derived from the "fieldInfo" complex type. It's an array of the "fieldInfo" complex type.
In simple terms, we've defined the object properties which will be returned in the response of the API method call. In our case, we'll return an array of products. Each item of an array will have two properties: "entity_id" and "name" of the product. You can define more properties as per your requirements.
Next, under the <message>
tag "customapimoduleProductListRequest", we've defined the input parameters required using the<part>
tag. In the same way, under the <message>
tag "customapimoduleProductListResponse", we've defined the type of the output objects. When we call an API method, we need to pass "sessionId", and the response of the API method will contain the array of products. The rest of the tags will make our method appear when you callhttp://yourmagentostore/api/v2_soap?wsdl=1.
Next, we'll need to create the "app/code/local/Envato/Customapimodule/Helper/Data.php" file just to make sure the translation system of Magento works properly. It's almost an empty file, but should be there as per the conventions!
1 | <?php |
2 | class Envato_Customapimodule_Helper_Data extends Mage_Core_Helper_Abstract |
3 | { |
4 | } |
Next, let's create a model file "app/code/local/Envato/Customapimodule/Model/Product/Api.php".
1 | <?php |
2 | // app/code/local/Envato/Customapimodule/Model/Product/Api.php |
3 | class Envato_Customapimodule_Model_Product_Api extends Mage_Api_Model_Resource_Abstract |
4 | { |
5 | public function items() |
6 | { |
7 | $arr_products=array(); |
8 | $products=Mage::getModel("catalog/product") |
9 | ->getCollection() |
10 | ->addAttributeToSelect('*') |
11 | ->setOrder('entity_id', 'DESC') |
12 | ->setPageSize(5); |
13 | |
14 | foreach ($products as $product) { |
15 | $arr_products[] = $product->toArray(array('entity_id', 'name')); |
16 | } |
17 | |
18 | return $arr_products; |
19 | } |
20 | } |
Recall that earlier in the "api.xml" we defined an "items" method wrapped by a <list>
tag. So in the above model class, we've just implemented this.
In this method, we simply fetch five recent products, and iterate through each of the items to prepare an array of products with the properties "entity_id" and "name". So now you should probably understand the reason for the"Complex Type" created in "wsdl.xml"!
Further, we also need to create a model file to support the Magento v2 API. Let's create a model file "app/code/local/Envato/Customapimodule/Model/Product/Api/v2.php" with the following contents.
1 | <?php |
2 | //app/code/local/Envato/Customapimodule/Model/Product/Api/V2.php |
3 | class Envato_Customapimodule_Model_Product_Api_V2 extends Envato_Customapimodule_Model_Product_Api |
4 | { |
5 | } |
As you can see, it's just extending a model class defined earlier in the "app/code/local/Envato/Customapimodule/Model/Product/Api.php" file.
So that's it as far as the file setup is concerned for the custom API implementation. If you're curious, enable the module from the back-end and clear the cache. Now, when you visit the http://yourmagentostore/api/v2_soap?wsdl=1 page, you should see our method "customapimoduleProductList" is listed along with the other APIs!
In the next part, we'll go ahead and see how to create API user and API role, and of course, how to use our custom API method defined in this tutorial!
FAQs
How to create custom API in Magento? ›
- Step 1: Create webapi. ...
- Step 2: Now Create a di. ...
- Step 3: Create a TestInterface.php at app/code/Mageants/Blog/Api/TestInterface.php.
- Step 4: Create Test. ...
- Step 1: Create a customer account.
- Step 2: Verify the above email and password.
- Determine Your Requirements. First, you'll need to determine your API requirements. ...
- Design Your API. Next, you'll need to consider API design. ...
- Develop Your API. Now, it's time to start developing your API product. ...
- Test Your API. ...
- Publish/Deploy Your API. ...
- Monitor Your API.
- you need to create an interface in your module's Api folder.
- then you need to define all the api methods that you want to expose to the web in the interface.
- all the methods should have a doc-block.
- in the doc-block @api must be defined.
Rest API in Magento 2 defines a set of functions used by the developers to perform requests and get responses using the HTTP protocol. By default, Magento 2 provides some predefined rest APIs like Product API, Order API, Customer data API with which you can take virtual control of everything happening on the site.
How much does it cost to build custom API? ›On average, it costs $20,000 to build a relatively simple API. This figure assumes that you're building a secure, documented, fully-featured API with the services of an experienced API developer based in the United States.
What is a custom built API? ›Custom APIs are an alternative to custom process actions. Custom process actions provide a no-code way to include custom messages but has some limitations for developers. Custom APIs provide capabilities specifically for developers to define their logic in code with more options.
Can I create a custom API? ›To create a Custom API: Step 1: Click the New Test button and select New Test API: Step 2: Enter a Name, Title and Summary. (Name is the name of the Java class whereas Title is the display name of the API.)
How to create API without coding? ›How to create an API Endpoint on the no-code platform AppMaster.io. Log into your account for an existing project. Go to Data Model Designer. In Data Model Designer you will see models with data that you want to process using the endpoints API.
How to create web API for beginners? ›- Create ASP.NET Web Application in Visual Studio. ...
- Select Web API Template. ...
- Review Project Files. ...
- Add a Controller. ...
- Add Controller Method. ...
- Now, build your project and run the above-mentioned URL format.
Creating your own RESTful API can be a great way to build a business around data you've collected or a service you've created, or it can just be a fun personal project that allows you to learn a new skill. Here's a list of 20 tutorials on how to design your own REST API!
How to create JSON REST API? ›
- First of all, ensure you have NodeJs and NPM installed.
- Create a folder name of your own choice on the desired location. For now, I have created with the name: Fake-APIs.
- Run npm init inside the folder. ...
- Run npm install — save json-server. ...
- We need to start our server now. ...
- You should see a file named db.
- Click on System and select integrations.
- Click on the Add New integration button.
- In Integration Info, enter the basic details such as Name, Email id and Password.
- Select API under Basic Settings and select “All” from the Resource Access drop down menu. ...
- Click on the Active button.
- Click on Done.
REST API uses web services and is based on request and response, whereas RESTful API works completely based on REST application and infrastructure. REST apps have strong protocols and pre-configured architecture layers as security measures, whereas RESTful apps have multi-layered transport protocols.
Does Magento have REST API? ›You can also create a dynamic REST API documentation set on your server with live data. Magento uses Swagger to display REST APIs for all installed products and allows you to try out the APIs.
What is the difference between an API and a REST API? ›An API, or application programming interface, is a set of rules that define how applications or devices can connect to and communicate with each other. A REST API is an API that conforms to the design principles of the REST, or representational state transfer architectural style.
Can I build an API for free? ›Amazon AWS Free Tier and Amazon API Gateway
AWS Free Tier offers free access to Amazon API Gateway and many other such services to you. With the free access comes limitations and the constraints limit you to 1 million API calls per month or 750,000 connection minutes.
You Should Probably Build an API If:
You want to access the same data in many different places or ways (eg: an internal dashboard and a customer-facing web app) You want to allow customers or partners limited or complete access to your data. You want to upsell your customers on direct API access.
How long does it take to build an API app? An API app usually takes 69 hours to build. However, an API app can be built in as few as 35 hours, or in as many as 104 hours. The exact timeline mostly depends on how complicated your app is.
What are the benefits of custom API? ›- Custom-built integrations. Custom API development services enable businesses personalized experience on streamlining collaboration and data sharing between their own applications and third-party applications. ...
- An enhanced interface. tailored for your needs. ...
- We also have. Ready to use Pre-built APIs.
How to Use an API. Developers can use almost any modern programming language (like JavaScript, Ruby, Python, or Java) for their own API coding.
What are the different types of APIs to build? ›
- Open APIs. Open APIs, also known as public APIs or external APIs, are available to any developer. ...
- Partner APIs. ...
- Internal APIs. ...
- Composite APIs. ...
- REST. ...
- SOAP. ...
- RPC.
Some languages and frameworks used to write APIs are better and more efficient than others. From our experience in developing enterprise APIs, we have found that Python, Flask, Node, JS, and Express are the best languages for building EFFICIENT web application APIs.
Do you need a license to use an API? ›An API license agreement, or Application Programming Interface agreement, is a legal contract that governs the use of APIs between the licensor and other developers or users who want to use the API. Generally, this agreement includes terms that heavily favor the licensor.
Do I need permission to use an API? ›As mentioned, an API key is used to identify yourself as a valid client, set access permissions, and record your interactions with the API. Some APIs make their keys freely available, while others require clients to pay for one. Either way, you'll most likely need to sign up with the service.
Is making an API easy? ›Creating your own APIs can seem daunting if you're new to the practice, but sticking to a design-first approach will keep you on the right track. A simple three-step process—design, verify, code—can increase your chances of building an API that benefits the people who use it.
What can I use instead of an API? ›- GraphQL. GraphQL is a runtime and query language for APIs that allows clients to request and receive only the data they require, making it more efficient than REST. ...
- gRPC. ...
- WebSockets. ...
- MQTT. ...
- Event-Driven Architecture (EDA) ...
- FALCOR. ...
- Functions.
- Start with your goals and intended users.
- Design the API architecture.
- Develop your API.
- Test your API.
- Monitor your API and iterate on feedback.
- Create a LoopBack application project called climbon in a climbon directory: apic loopback --name climbon.
- Update the API and application development artifacts.
- Test the project (service) locally. ...
- Update the API and application development artifacts as required.
Turn any website into an API without writing a single line of code. Browse AI can quickly generate a custom API for any website, even if it doesn't have an existing API. Easily access and use the data you need from the website for your projects with the greatest flexibility and control.
Is making a REST API hard? ›REST API development isn't as easy as writing a web app or an HTML document. You must follow specific rules and best practices to ensure that your API is secure, reliable, and scalable. If you take things one step at a time, however, you'll end up with an application that provides tremendous value to your users.
What is the difference between JSON and REST API? ›
While SOAP and REST are both leading approaches to transferring data over a network using API calls, JSON is a compact data format that RESTful web services can use. Deciding whether you should create a SOAP vs REST API is an essential question if you are planning to provide a web service.
What is the difference between API and JSON? ›The user and the server send a data request in the API. The API then designates how the data will be called using the GET method and the affiliated links shared. A JSON object then retrieves data and outputs either an error message or shows data depending on the user request.
What is the difference between JSON and JSON API? ›JSON can be classified as a tool in the "Languages" category, while JsonAPI is grouped under "Query Languages". Redsift, Mon Style, and Mercedes-Benz.io GmbH are some of the popular companies that use JSON, whereas JsonAPI is used by Firecracker, Tricentis Flood, and Rad.
What are methods to create Magento API integration? ›- In the Magento backend admin panel navigate to System > Extensions > Integrations.
- With the Add new integration button create a new integration form.
- Specify the integration name, for example myintegration.
- Create a local API definition YAML file.
- Validate the API definition.
- Create a local Product definition.
- Validate the Product definition.
- Log in to API Manager.
- Publish the Product to API Manager.
- In the web app, navigate to User Icon My Profile User Settings.
- In the section API Access, click Create API User Token.
- Enter a Description to help you identify the key later.
- Click Create Key.
A general rule of thumb when you're deciding between SOAP and REST for building your API: if you want standardization and enhanced security, use SOAP. If you want flexibility and efficiency, use REST.
Why is REST called REST API? ›REST stands for Representational State Transfer. This means that when a client requests a resource using a REST API, the server transfers back the current state of the resource in a standardized representation.
How many types of API are there? ›There are four different types of APIs commonly used in web services: public, partner, private and composite.
How does Magento API work? ›Magento API is a type of framework that offers developers and integrators a good method to maximize web services which communicate well with the Magneto system. Amongst the primary features are supports for SOAP (Simple Object Access Protocol) and REST (Representation State Transfer).
What types of API does Magento Commerce have? ›
It offers three types of authentication: 1) OAuth 1.0a for third-party application authentication, 2) the tokenization method for mobile application authentication, and 3) login credential for administration and customer verification. You can configure any Magento or third-party web API by writing a few lines of XML.
How to connect to Magento API? ›In Subscribe Pro, go to System > Configuration and click on the Store Connection Settings tab. Under E-commerce Platform Connection Type select Magento 2 REST API. Under the Magento 2 REST Connection heading, set M2 REST API Base URL to the base URL of your Magento 2 store.
Why are REST APIs better? ›The benefits of REST APIs are endless
REST APIs are also efficient, high-performing, consume less bandwidth, and are cost-effective because developers can use them without third-party tools.
The majority of HTTP APIs are on the verge of becoming completely RESTful. But not all HTTP APIs are REST APIs. To be termed a REST API, the API must meet the following architectural requirements: Client-Server: A server oversees the application's data and state in REST applications.
What is REST API with example? ›A RESTful API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources.
How to create CRUD API in Magento 2? ›- Step 1 – Create Database Schema. To create the database table for CRUD operation initially insert the Setup file (InstallSchema.php): ...
- Step 2 – Create Module. Name of the module is defined as /. ...
- Step 3 – Read Data from Table and Display. Create Model. ...
- Step 4 – Insert Record. ...
- Step 5 – Update Record. ...
- Step 6 – Delete Record.
- Step 1: Send payment information.
- Step 2: Review the order as an admin.
- Step 3: Verify this step.
- Create Web API Project. In the New Project popup, select Web template under Visual C#. ...
- Select Web API Project Template. ...
- Change Authentication. ...
- Web API Project. ...
- Create Entity Data Model. ...
- Generated Entities in the EDM Designer. ...
- .edmx in the Project. ...
- Create Web API Controller.
- Step 1: Create a web services user on Magento Admin. If the authentication that you are using is token-based, selecting System > Permission > All Users > Add New User . ...
- Step 2: Create a new integration on Magento Admin. ...
- Step 3: Configure authentication.
CRUD stands for Create, Read, Update, and Delete, which make up these four fundamental operations. Because REST API calls invoke CRUD operations, understanding their relationship with one another is important for API developers and data engineers.
What is a custom API key? ›
A custom API key is a private key you can configure in Ortto to allow 3rd-party applications to interact and perform activities with your Ortto account's data through Ortto's public application programming interface (API), known as the Ortto API.
How to create API token in Magento 2? ›To get a token, you need to specify the user's name and password in the payload. By default, an admin token is valid for 4 hours. To change this value, please access to your admin panel and navigate to Stores > Settings > Configuration > Services > OAuth > Access Token Expiration > Admin Token Lifetime (hours).
How to create product using REST API in Magento 2? ›- Navigate to System > Extensions > Integration.
- Click Add New Integration button.
- Enter your Name and admin Password.
- Click save and active button.
- Click Allow. Now the Authentication key is generated.
Token is an electronic key which allows users to access the API and Magento development is having three types of tokens as below. Step 1: Login as Admin and go to System & Integrations. Step 2: Click on “Add New Integration”. Step 3: Provide a unique name for the integration in the Name field.
How to get product list API in Magento 2? ›In order to fetch the list of all products in the Magento 2 store using API, we will be using the GET method. The client needs to make a GET all to store_url/products with the PageSize value in the search criteria. The value of PageSize will define the number of products to be displayed per page.
What are all the API methods? ›- HTTP resources vs. resource collections. ...
- Method 1: POST. ...
- Method 2: PUT. ...
- Method 3: PATCH. ...
- Method 4: GET. ...
- Method 5: DELETE.
The Magento web API framework provides integrators and developers the means to use web services that communicate with the Magento system.