How To Start With Magento 2 API

how-to-start-with-magento-2-api
Posted in: Magento 2 Guides

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 (Magento customer API)
, 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.

Where can you find the Magento 2 rest API list of info?

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. Here you can find the one-stop Magento 2 REST API list of info.

See what Amasty's extensions support API

How Magento 2 API Works

Magento 2 supports 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: /vendor

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.

What is the Magento 2 Swagger API for?

Magento 2 uses built in Swagger 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.

What about Magento 2 REST API URL? To be able to use swagger you need to add “swagger” to your website URL, for example:

http://abc.com/swagger

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 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 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:

How to create new Magento integration API?

To create a new integration, please, navigate to System >> Extensions >> Integration >> Add New Integration.

In “Integration info” tab you need to specify Name, Email, Callback URL and Identity link URL, which makes the user redirected to link his 3rd party account with Magento integration access details.

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.

Once all changes will be applied you need to enter your current admin password and click “Save”. To proceed using integration, please click Activate and confirm your choice.

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:

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: http://magento.m2/rest/V1/customers/me

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:

  1. Enter Magento Admin and navigate to System >> Extensions >> Integrations >> Add new integration.
  2. 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.

checklogin.php example:

endpoint.php example:

login.php example:

OauthClient.php example:

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.

April 2, 2018
April 4, 2018
March 2, 2018
Comments
Pankaj
July 25, 2018
Dear Yuliya Thanks for the beautiful post. Magento has the customer authentication with username and password. But for same magento website how can we create registration API with only mobile number and login with mobile number and password .
Reply
PAM
August 29, 2019
Hi! How can I increase the security level of the admin login?
Reply
Polina Litreyeva
August 29, 2019
Hello, Pam. Thank you for your question. Take a look at the <a href="https://amasty.com/two-factor-authentication-for-magento-2.html">Two-Factor Authentication</a> extension. This plugin allows you to use the Google Authenticator mobile app as the second step of authentication.
Martin
September 4, 2019
Wonderful points. This is very helpful for me. Thanks for sharing. I will definitely try it.
Reply
Polina Litreyeva
September 13, 2019
Hi, Martin! Thanks for reading and sharing your opinion. We are glad that our articles are valuable.
Piterson
September 5, 2019
Thanks for this article. Sometimes I send this link to my newbies :)
Reply
Polina Litreyeva
September 5, 2019
Hello, Peterson. We are glad to receive your feedback, it’s an inspiration for our team.
Victor Cortez
September 10, 2019
Is the token specific locally or is it transferable? Does a token need to be created from each place that is connecting to the api?
Reply
Polina Litreyeva
September 19, 2019
Hello, Victor. Usually, a token has a limited lifetime - 4 hours. But you can change it in settings. Go to <strong>Stores > Settings > Configuration > Services > OAuth > Access Token Expiration > Admin Token Lifetime (hours)</strong> and set needed value. If you still have questions, feel free to send a word to our support team at <a href="mailto:support@amasty.com" rel="nofollow">support@amasty.com</a>, they will be happy to help you.
Dushyant Joshi
October 11, 2019
One stop information for REST api in Magento2. Thank you for sharing.
Reply
Polina Litreyeva
October 14, 2019
Hello, Dushyant! Thanks for your comment! We are always happy to be helpful.
Dushyant Joshi
October 12, 2019
Where should I place OauthClient.php & checklogin.php files?
Reply
Polina Litreyeva
October 14, 2019
Hi, Dushyant! Thanks for your feedback. You can add these scripts to your site root directory.
DAN
February 10, 2020
Hi Polina, Thanks for your sharing, really help. I got a quick question regarding your steps. If I run the swagger endpoint for tokens I'm getting: { "message": "The account sign-in was incorrect or your account is disabled temporarily. Please wait and try again later." } Do you know how to solve it? Thanks, Dan
Reply
Polina Litreyeva
February 14, 2020
Hi, Dan. Thanks for reading! You see, the question needs professional assistance with deeper insights into the system itself, as long as there are multiple reasons why the issue could occur. Sorry but that is why we won’t help you in the comments. Cheers!
Ram
February 28, 2020
Hi Polina, In my Magento site shows message like 'It's time to change you password' so i changed my password after enter in my magento account it working fine but I try to get a token using API but i got response like ''The account sign-in was incorrect or your account is disabled temporarily. Please wait and try again later."
Reply
Polina Litreyeva
March 2, 2020
Hi, Ram. Thanks for your comment! You see, there are various reasons why the problem could happen, and we need to dive deeper into the system itself to answer your question. Sorry but that is why we won’t help you in the comments. Cheers!
Priyanka
October 18, 2020
how can we update customer data.. with PUT method and using customer token as a authorisation?
Reply
Alina Bragina
October 30, 2020
Hi Priyanka, please, write to us at support@amasty.com and our managers will help you out. Cheers.
Leave your comment

Your email address will not be published

This blog was created with Amasty Blog Pro

This blog was created with Amasty Blog Pro

© 2009-2022 Amasty. All Rights Reserved.