If you're using Magento 2, you're likely familiar with the term API. However, understanding what it truly encompasses, how it operates, and its significance for your e-commerce business is indispensable
In this article, we'll provide an in-depth look at Magento APIs, explaining their functionality and types as well as share detailed guides on generating keys and tokens. We’ll also show you how to create an integration in Magento 2 with code examples from our Magento integration experts.
What is Magento API?
At its core, an API is a set of protocols that allows different software systems to communicate with each other. Magento 2's API framework allows your e-commerce platform to interact with third-party services, such as payment gateways, social media logins, inventory management tools, and more.
When you're using an API, you send a request to an external service (like Facebook, PayPal, or your PIM system) and receive an API response with the required data. For example, when a customer logs into your Magento 2 store using their Facebook credentials, Magento requests data from Facebook through an API, processes it, and grants access accordingly.
How Does an API Work in Magento
To understand how Magento's API works, let's break down the components of an API call in Magento 2. Each Magento API call consists of several key elements:
- HTTP verbs – These define the actions performed on an endpoint, such as GET, PUT, POST, and DELETE.
- Endpoint – The URL that specifies the server, web service, and resource being accessed, along with any template parameters.
- Call payload – Contains the input attributes and parameters sent with the request. These can be required or optional and may be specified either in the URI or within the request body. Magento supports both JSON and XML-formatted request bodies.
- HTTP headers – Provide metadata for the request and response, including information about authentication, caching, and cookies.
These components work together to enable seamless API communication. The HTTP verbs dictate the action on the resource, such as retrieving or updating data, and the endpoint directs the request to the specific resource on the server. The payload then carries the necessary data for the operation, while the headers provide essential metadata, like authentication credentials.
For example, a GET request to an endpoint like /orders/123 retrieves the order details, and the payload might include the user's authentication token for secure access.
Types of APIs in Magento 2
Magento 2 supports different API types, each designed for specific use cases and performance needs. Let’s explore these options in detail.
REST API
REST (Representational State Transfer) is a stateless, lightweight API that allows interactions between systems with minimal overhead. It’s commonly used in mobile applications, SPAs, and external systems that need to interact with Magento.
SOAP API
SOAP (Simple Object Access Protocol) is a protocol-based API designed for applications that require a high level of security and transactional reliability. This API uses XML messaging to request and return data, ensuring that communication is both structured and secure. SOAP is particularly beneficial for integrations with legacy systems and high-security environments, as it can provide stricter data integrity checks.
GraphQL
GraphQL is a modern query language for APIs, which allows clients to request exactly the data they need. Unlike REST, where clients may receive more data than necessary, GraphQL optimizes data fetching, especially for front-end development. This is useful for complex interfaces where clients need multiple data resources with a single request, reducing server load and improving performance.
Read More: How to Use GraphQL in Magento 2
What is Magento 2 REST API Swagger?
Magento 2 API Swagger provides an interactive interface for exploring and testing the available REST API methods. Magento 2 Swagger generates real-time REST API documentation based on your instance, offering detailed information on endpoints and allowing you to execute API calls directly from the browser.
To access the Magento Swagger UI, append /swagger to your site’s URL (e.g., http://abc.com/swagger). Here, you can view available API methods, make test requests, and see responses, enhancing both development and debugging workflows.
Authentication Methods in Magento 2
Magento 2 supports multiple authentication methods to secure API access and ensure that only authorized users interact with your store. The authentication type depends on the API being used (REST, SOAP, or GraphQL) and the required security level.
Token-Based Authentication
- Commonly used for Magento RESTAPI and GraphQL APIs.
- Requires a username and password to generate a unique access token.
- The token is included in API requests as a Bearer token for stateless authentication.
Example use case: A customer or admin retrieves a token and uses it for multiple API requests until it expires.
Session-Based Authentication
- Typically used for user-specific actions like login and profile updates.
- Maintains an active session for API calls.
- Primarily associated with SOAP API but also applicable to personalized Magento operations.
Example use case: A logged-in user updates their profile via API without re-authenticating.
OAuth Authentication
- Ideal for third-party application integrations requiring delegated access.
- Supports both REST and SOAP APIs.
- Allows external applications to interact with Magento data without exposing user credentials.
Example use case: A payment gateway or ERP system securely connects to Magento via OAuth-based authentication.
Magento 2 API Access Tokens and Keys
Magento 2 provides two primary methods for secure API access:
- API Access Tokens are used for temporary authentication as an Admin or Customer and typically expire after a set duration. They are obtained via a login request and included in API calls as a Bearer Token.
- API Keys (OAuth Credentials) are used for persistent authentication in third-party integrations and do not expire unless revoked. API keys are generated in Magento’s Admin Panel under System > Integrations.
Authentication Method | Best For | Expiration |
---|---|---|
API Access Tokens | Admin & Customer Sessions | Temporary |
API Keys (OAuth) | Third-Party Integrations | Persistent |
How to Get Admin API Access Tokens for Admin
For temporary authentication when making API requests as an Admin, follow these steps:
1. Send an Authentication Request. Use cURL or Postman to obtain an access token:
1. Send an Authentication Request. Use cURL or Postman to obtain an access token:
curl -X POST --header 'Content-Type: application/json'
--header 'Accept: application/json' -d '{ \ "username": "%username%", \ "password": "%password%" \ }' 'http://magento2.url/default/rest/all/V1/integration/admin/token'
2. You will receive a token that will look like `bnkte0ubwdbnqebyfct29pq0hg1vpu0t'.
3. Include this token in all subsequent API requests using the Authorization header.
How to Get API Keys for Magento Third-Party API Integration
To securely integrate external applications with Magento 2 using OAuth, follow these steps:
- Access the Integrations Panel: In the Magento Admin, go to System > Extensions > Integrations, and click Add New Integration.
- Enter Integration Details: Provide a unique name (e.g., SomeUniqueIntegrationName), callback URL (e.g., http://your_app_host/endpoint.php), and identity link URL (e.g., http://your_app_host/login.php).
- Assign API Permissions: Specify the necessary permissions in the API tab to control access.
- Authenticate & Retrieve Keys: Click Activate. After authorizing the integration, you will receive OAuth credentials, allowing secure API communication.
Custom Magento API Integration: How to Create API Requests in Magento 2?
Magento 2's API offers a powerful way to extend and integrate your store with other services. Let’s explore the steps in using the API for your Magento 2 store, from setup to integration.
In our examples, we will focus specifically on how to perform Magento 2 third-party API integration within a Magento module, using real examples to guide you through the configuration and implementation process.
Step 1: Declare the API in webapi.xml
Magento 2 uses the webapi.xml file to define API routes and specify which classes handle requests. This file is essential for exposing custom APIs via REST or SOAP.
- Navigate to your module’s etc/ directory.
- Create a webapi.xml file if it doesn’t exist.
- Define an API route using an XML structure.
Once webapi.xml is configured, Magento knows how to route requests to the appropriate class and method.
Step 2: Define the Service Interface
Magento 2 follows the Service Contract pattern, requiring an interface to define API logic.
- Navigate to Vendor/Module/Api/.
- Create CustomInterface.php.
For example:
namespace Vendor\Module\Api; interface CustomInterface { /** * Retrieve custom data * @return string */ public function getData(); }
At this stage, we have only defined what the API should do. The next step is implementing it.
Step 3: Create Model Classes
With the interface defined, the next step is to create the model classes that implement the business logic for your API. The model classes are responsible for processing the data, handling database operations, and returning the correct response to the API request.
- Navigate to Vendor/Module/Model/.
- Create Custom.php.
Magento 2’s MVC (Model-View-Controller) structure helps separate concerns, so you can focus on the logic needed for your API without worrying about the rest of your application.
Step 4: Implement the API Logic in the Repository
Once your service interface and model class are set up, it’s time to implement the actual logic that will handle API requests. This might involve data validation, querying the database, processing user input, and formatting the output before sending the response.
Creating the Repository Class
- Navigate to Vendor/Module/Model/.
- Create CustomRepository.php.
Step 5: Test the API
Once the API is implemented, testing ensures it works as expected.
Testing via Postman
- Open Postman or a similar API client.
- Set the request type to GET (or the appropriate method).
- Enter the API URL: https://yourstore.com/rest/V1/customapi/get
- Add an Authorization header with a valid Bearer token.
- Click Send to execute the request.
Expected response: "message": "Data retrieved successfully"
Read More: How to Test Magento 2 API with Postman? [backend] + [frontend]
Testing via cURL
Run the following command in the terminal:
curl -X GET "https://yourstore.com/rest/V1/customapi/get" -H "Authorization: Bearer "
Step 6: Implement API Authentication and ACL Rules
Magento 2 enforces access control via ACL rules in acl.xml.
1. Navigate to Vendor/Module/etc/adminhtml/acl.xml.
2. Define permissions.
3. Assign permissions in Admin Panel under System > Permissions > User Roles.
Best Practices for Custom API Development in Magento 2
Developing custom APIs in Magento 2 requires careful planning to ensure performance, security, and maintainability. Following the best practices of API Integration services providers and API development companies can help you create robust and scalable APIs that integrate seamlessly with other systems.
- Follow Service Contracts – Always use interfaces for API logic.
- Secure API Endpoints – Enforce ACL rules and authentication.
- Validate Input Data – Prevent security risks by sanitizing input.
- Use Magento’s Logging System – Debug issues efficiently with \Psr\Log\LoggerInterface.
- Ensure Backward Compatibility – Maintain older API versions when updating.
Troubleshooting and Support for Magento API
Working with Magento APIs can be challenging, especially when encountering issues that hinder smooth integration. Here’s a comprehensive guide to tackling common problems:
Authentication Errors
Authentication errors often occur due to incorrect API keys, expired tokens, or insufficient permissions. Here’s what you can check to resolve these issues:
- Check API Keys – Ensure that the API keys are correctly set up in Magento's admin panel and that they are linked to the right integration.
- Validate Access Token – Confirm that the access token you’re using hasn’t expired. Tokens typically have an expiration time, so ensure it’s refreshed as needed.
- Verify Permissions – Review the API user permissions to ensure they have the necessary access to execute the required actions. Missing permissions can lead to authentication failures.
Read More: Project Authentication Error Solution in Magento API
Response Errors
Response errors, like 401 or 403, are usually caused by incorrect endpoint URLs, missing or invalid authentication credentials, or improper ACL settings. Here are steps to resolve these issues:
- Endpoint URLs – Ensure the API endpoints are accurately typed and correctly point to the desired resources within your Magento instance. A typo or wrong path can cause a 401 (Unauthorized) or 403 (Forbidden) error.
- Request Headers – Check the request headers for proper authentication credentials. For example, ensure the Authorization header contains the correct Bearer token or API key for API calls. Missing or incorrectly formatted credentials may trigger authentication errors.
- ACL Settings – Review your Access Control List (ACL) settings to ensure the right permissions are assigned to the API user or integration. Missing or incorrect ACL rules may block access to certain resources, resulting in a 403 error. Verify that your API user has the required permissions to access the specific API method or resource.
Read More: How to Fix Errors 401 and 403
Performance Issues
If you're facing performance issues, the root cause may lie in inefficient queries, large payloads, or outdated cache. Here are some tips for improving performance:
- Profile API Calls – To identify slow or inefficient queries, utilize Magento’s profiling tools to monitor the performance of API calls. Profiling helps pinpoint which queries consume the most time, allowing you to optimize them.
- Optimize Payload – Minimize the data requested by specifying only the necessary fields in your API call. This reduces the load on the server and improves response times, especially for large datasets.
- Clear Cache – Refresh your cache to ensure that recent changes, such as updates or new configurations, are applied correctly. Outdated cache can cause inconsistent results or slow down API performance.
Read More: Full Guide to Magento Caching
Delegate Magento API Integration to Amasty
For ongoing support and expertise, consider Amasty’s Integration Services. We offer comprehensive Magento integration services, assisting businesses in connecting seamlessly with platforms like SAP Business One ERP, Salesforce, Amazon, QuickBooks, and PIM systems.
The Amasty team helps Magento store owners set up, troubleshoot, and optimize API integrations efficiently. With our expertise, we ensure smooth data exchange, optimized workflows, and improved scalability, while providing tailored solutions to reduce errors and accelerate time-to-market.