It is not a surprise for everyone that Magento 2 API is used for third party services communication with the Magento platform. Despite the fact that this topic is extensively considered in the Magento community, there are still questions on the API usage.
This article will explain your very first steps of using Magento 2 API. API lets you speed up getting, sending and processing data, be it products, customers, or orders, and also transferring it to the third party system (any software for stock management, project management, and such). Obviously, automatic data transfer is way faster and easier than manual export and import.
Let’s see a clear example. Say, you want to log in via Facebook on your website and you have our module Social Login. This plugin uses Facebook API to provide fast access to the needed data.
To enable the API you set Consumer Key and Consumer Secret in your Admin panel. See how it looks in backend here.
The first part of the article talks about the general Magento 2 API configuration, and the second part is more practical, explaining the way of using API via Swagger, which is the basic tool for checking API methods.
This article will be useful for those Magento users which possess starting development knowledge and wish to explore the advanced part of Magento, and also for junior Magento 2 developers.
How Magento 2 API Works
Magento 2 supports 2 types of API: REST (Representational State Transfer) and SOAP (Simple Object Access Protocol), like it was in the previous Magento versions. We will more refer to REST API integration as it is less strict then SOAP API.
To be able to tap into API framework we need to indicate URL in webapi.xml ( path: <module root dir>/vendor/<vendor-name>/<module-name>/etc/webapi.xml) and determine available services and methods for further API requests.
Once service class was defined in webapi.xml file, the system makes service method being rendered on the fly into web API.
Due to the fact that it is being formed automatically, it is essential for the service class to be formatted a particular way.
Each Magento API call is incorporated with an elements sequence, such as:
- HTTP verbs, which are actions executed against endpoint. Those are GET, PUT, POST, DELETE.
- Endpoint, which stands for URL that defines server, web service, the resource against which the request was executed and template parameter.
- Call payload, contains all input attributes and parameters supplied with the request. API operations input can be both required and optional. One can indicate input parameters in the URI and input attributes in a body of the request. It is possible to use either JSON- or XML-formatted request body.
- HTTP header renders request and response body info, request authorization, response caching and cookies. It stands for meta-data representation and connected with the API request and response.
Magento 2 uses built in tool (which is shipped with each Magento 2 instance) for immediate REST API documentation generation.
The distinctive feature of this tool is that demonstrates methods available for your particular Magento instance, so its a kind of plus to always get access to up-to-date information on your website.
Another eye-catching feature of Swagger is endpoints execution directly from the browser so you are always able to check what return values are.
To be able to use swagger you need to add “swagger” to your website URL, for example:
Once you are redirected to swagger page you can see all methods available for guest user.
Magento 2 API User Types And Creating A New Integration
Here we need to direct our attention to the fact that there are three user types that have access to API in Magento 2 and those are:
1) Guest user, with access to resources with anonymous permissions.
2) Administrator with access to resources allowed by admin settings.
To be able to use methods available for admin user you need to proceed with authentication with the help of API key to get access to the full set of API endpoints.
This can be done via the integrationAdminTokenServiceV1 endpoint:
You`ll need to indicate login and password and click “Try it out” button. The returned value needs to be pasted into the api_key field:
To create a new integration, please, navigate to System >> Extensions >> Integration >> Add New Integration.
In the “API” tab you need to select either All or Custom resource access, depending on the functionality you would like to make available for the user.
3) Customer with self or anonymous permissions access to the resources.
Magento 2 API Authentication Types
There are three types of authentication that we can use:
1) Token-based authentication.
The idea is to provide the username and password during initial connection and receive the token to be used for requests that follow, until token expires.
You can use curl to get token and then send request with this token to get necessary information.
For example: You will receive a token which will look like `bnkte0ubwdbnqebyfct29pq0hg1vpu0t` and then all queries should contain this token. For example, let’s get cms blog by ID: You will get the following response:You will get the following response: Also, you can use SOAP to get the same data.
The SOAP requests will receive authorization token and return a function to get the enabled modules.
2) Session-based authentication, which is the simplest one.
Briefly, Magento 2 API framework uses user session for the requested resource access authorization.
For example, create frontend user, log in and point your browser to this page:
As a customer, you will be authorized to access resources with self and anonymous permission. However, it also works for admin accounts if you try to access a resource for which your admin account has permission .
3) OAuth-based authentication, which presents Magento 2 API as a service for a third-party resource access via getting approval got from the resource owners.
To process with OAuth you need to follow below steps:
- Enter Magento Admin and navigate to System >> Extensions >> Integrations >> Add new integration.
- Fill in the details in the Integration Info tab, for example:
- Name: SomeUniqueIntegrationName
- Callback URL: http://your_app_host/endpoint.php
- Identity link URL: http://your_app_host/login.php
- Add required permissions on the APItab
After you click Save and Activate you will see pop-up window, where you need to confirm API permissions. Access details are posted to endpoint.php.
You will see one more pop-up which starts identification which opens a script from login.php.
When you click “Login” – you are calling checklogin.php script which uses posted access details to finalize token exchange. When token exchange was completed successfully, you will be redirected back to the “Integrations” grid. This new integration will be displayed with the Active state.
If you click on “Edit” label and check Integration details, you will be able to see the access details which can be used to make an authenticated API call via Oauth. Below is the list of examples for Magento 2 API authentication.
That’s a wrap for today! Now, if you want to proceed with Magento 2 API usage, you can check which methods are built in Magento 2 and third-party extensions to know how to pass the information to the needed system.
Have any questions at this point? Feel free to ask them in the comments section.