Magento 2 Rest API: What Is It and How to Use It to Create a Custom API Module

Contact Us

×

Get a Free Consultation

Your Magento store doesn’t live in isolation. It needs to talk to ERPs, CRMs, mobile apps, third-party logistics systems, and more — and the Magento REST API is what makes that possible. But for many developers, the jump from understanding what the API does to actually building a custom endpoint can feel unclear.

This guide explains how the Magento 2 REST API works, covers the key endpoints you’ll use most, and walks through exactly how to create a custom Magento REST API module — with code you can apply directly.

Summary

  • The Magento REST API supports CRUD operations across products, customers, orders, and categories.
  • Magento 2 offers three authentication methods: OAuth 1.0, token-based, and session-based.
  • Swagger provides a built-in interface to explore and test available API endpoints.
  • Creating a custom Magento 2 REST API module requires four core files: module.xml, webapi.xml, di.xml, and the model class.
  • Proper access control and error handling are essential before deploying custom APIs to production.

What Is the Magento REST API?

REST (Representational State Transfer) is an architectural standard for building web APIs. The Magento REST API allows external systems to interact with your store’s data — reading, creating, updating, and deleting records through standard HTTP methods.

If you’ve ever connected Magento to a NetSuite ERP, a Salesforce CRM, or a custom mobile app, you’ve used the REST API. It’s the primary bridge between Magento and the outside world. You can also explore Magento API integration best practices to understand the full scope of use cases before building your first endpoint.

REST API vs. GraphQL in Magento 2

Magento 2 supports both REST and GraphQL. Here’s a quick comparison to help you choose the right approach:

Feature REST API GraphQL
Use case Server-to-server, ERP/CRM integration Frontend-heavy, PWA, headless commerce
Response format JSON or XML JSON only
Flexibility Fixed response structure Request only the fields you need
Learning curve Lower Moderate
Best for Back-end integrations Storefront data fetching

For most B2B integrations and back-end workflows, the Magento 2 REST API remains the standard choice.

Magento 2 REST API Authentication Methods

Before making any API call, you need to authenticate. Magento 2 supports three methods depending on your integration type.

OAuth 1.0

OAuth 1.0 is the standard for third-party app integrations. It uses a token-exchange flow — the client and server exchange keys to verify identity without transmitting credentials directly. This is the recommended method for integrations you deploy to external platforms.

Token-Based Authentication

Administrators and customers can generate access tokens through the Magento admin panel or via API. These tokens are passed in the request header for all subsequent calls, eliminating the need to send usernames or passwords each time. This is the fastest method to get started with during development.

Session-Based Authentication

For logged-in web sessions, Magento 2 supports session-based authentication. This is typically used in browser-based flows where a user is already authenticated through the storefront.

Authentication method summary:

Method Best For Security Level
OAuth 1.0 Third-party app integrations High
Token-Based Admin/customer integrations Medium–High
Session-Based Logged-in storefront sessions Medium

Setting Up API Credentials in Magento 2

To start making authenticated API calls, you’ll need to create an integration and generate credentials from the Magento Admin Panel.

Step-by-Step: Creating an Integration Token

  1. Log in to the Magento Admin Panel.
  2. Go to System > Extensions > Integrations.
  3. Click Add New Integration.
  4. Fill in the name, email, and other required fields.
  5. Under the API tab, select the resource permissions this integration needs.
  6. Save and activate the integration.
  7. Copy the Consumer Key, Consumer Secret, Access Token, and Access Token Secret.

Once you have these credentials, include the Access Token in the Authorization header of every API request:

Authorization: Bearer YOUR_ACCESS_TOKEN

Core Magento 2 REST API Endpoints

The Magento REST API exposes endpoints for every major entity in the store. Here’s a reference for the most commonly used ones.

Product Endpoints

Operation Method Endpoint
Get all products GET /V1/products
Create product POST /V1/products
Update product PUT /V1/products/{sku}
Delete product DELETE /V1/products/{sku}

The GET /V1/products endpoint supports filtering, sorting, and pagination. For example, you can filter by attribute set, status, or price range using searchCriteria query parameters — making it flexible enough to power catalog sync workflows with external systems.

Other Key Endpoints

Entity Base Endpoint
Customers /V1/customers
Orders /V1/orders
Invoices /V1/invoices
Categories /V1/categories
Carts /V1/carts

For a full reference, Magento’s built-in Swagger interface (covered below) lists every available endpoint with input parameters and expected responses.

Using Magento Swagger to Explore the API

Magento 2 includes Swagger UI, a browser-based tool that lets you view and test all available REST endpoints without writing a single line of code.

How to Access Swagger

  1. Set your Magento instance to Developer Mode.
  2. Navigate to: https://your-store.com/swagger
  3. Authenticate using your access token.
  4. Browse endpoints by entity, test calls, and inspect responses live.

Swagger is especially useful during the planning phase of a new integration. Before you write code, you can confirm which endpoints exist, what parameters they accept, and what the response structure looks like. It’s the fastest way to validate your approach before committing to a build.

How to Create a Custom Magento 2 REST API Module

The built-in endpoints cover standard operations, but real business needs often require custom logic. A custom Magento 2 REST API module lets you expose your own endpoints — tied to whatever back-end logic your integration requires.

Here’s the full step-by-step process.

Step 1: Define the Module

Create the module registration files at: app/code/Folio3/CustomApi/registration.php and app/code/Folio3/CustomApi/etc/module.xml

xml

<!-- etc/module.xml -->

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">

    <module name="Folio3_CustomApi" setup_version="1.0.0"/>

</config>

Step 2: Register the Route in webapi.xml

Create app/code/Folio3/CustomApi/etc/webapi.xml to define your API endpoint, HTTP method, service class, and access control:

xml

<?xml version="1.0"?>

<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">

    <route url="/V1/folio3/customapi" method="POST">

        <service class="Folio3\CustomApi\Api\ContentInterface" method="saveDetail"/>

        <resources>

            <resource ref="Magento_Customer::manage"/>

        </resources>

    </route>

</routes>

Avoid using anonymous access unless your endpoint is intentionally public. Anonymous endpoints are accessible without authentication and pose a security risk if they expose sensitive data or write operations.

Step 3: Declare the Interface

Create the interface at app/code/Folio3/CustomApi/Api/ContentInterface.php:

php

<?php

namespace Folio3\CustomApi\Api;

interface ContentInterface

{

    /**

     * @return string

     */

    public function saveDetail();

}

Magento uses this interface — not the concrete class — for dependency injection and type checking. Always define your API methods in an interface first.

Step 4: Register the Preference in di.xml

Create app/code/Folio3/CustomApi/etc/di.xml to map the interface to its implementation:

xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <preference for="Folio3\CustomApi\Api\ContentInterface"

                type="Folio3\CustomApi\Model\Content"/>

</config>

Step 5: Implement the Model Class

Create app/code/Folio3/CustomApi/Model/Content.php with your business logic:

php

<?php

namespace Folio3\CustomApi\Model;

class Content implements \Folio3\CustomApi\Api\ContentInterface

{

    public function saveDetail()

    {

        // Your custom logic here

        return 'Success';

    }

}

Step 6: Enable the Module

Run these commands from your Magento root:

bash

php bin/magento module:enable Folio3_CustomApi

php bin/magento setup:upgrade

php bin/magento cache:clean

Your new endpoint is now live at /V1/folio3/customapi and accessible via POST with a valid bearer token.

Common Mistakes to Avoid When Building Custom Magento REST APIs

Even experienced developers run into the same pitfalls. Here’s what to watch for:

  • Using anonymous access unnecessarily. Any endpoint with <resource ref=”anonymous”/> is open to the public. Restrict access to the minimum required role unless the endpoint is intentionally public-facing.
  • Missing PHPDoc blocks on interface methods. Magento’s serializer relies on PHPDoc type hints to process request and response data correctly. Missing or incorrect annotations cause silent failures that are hard to debug.
  • Skipping input validation. Your custom model should validate all incoming data before processing. Never assume the API consumer will send clean inputs.
  • Not running setup:upgrade after changes. Magento caches module configurations. Skipping this step after modifying di.xml or webapi.xml will cause your changes to have no effect.

Magento REST API Security Best Practices

Security isn’t optional when exposing API endpoints — especially on stores that handle customer data and order information.

Practice Why It Matters
Use token-based auth for all integrations Avoids credential exposure in every request
Restrict resource permissions in webapi.xml Follows least-privilege access principles
Rate-limit API endpoints Prevents abuse and DDoS-style request floods
Validate and sanitize all inputs Protects against injection and malformed data
Log API activity Enables auditing and anomaly detection

For stores handling sensitive customer or payment data, consider using Magento POS integration patterns as a reference for secure, multi-system communication.

Key Takeaways

  • The Magento REST API uses standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations on store entities.
  • Token-based authentication is the fastest method for development; OAuth 1.0 is recommended for production third-party integrations.
  • Creating a custom Magento 2 REST API module requires four files: module.xml, webapi.xml, di.xml, and the model class.
  • Always define API methods in an interface before implementing the model — Magento’s DI system depends on it.
  • Avoid anonymous access on write endpoints and always validate inputs before processing.

Conclusion

The Magento REST API gives you the flexibility to connect your store with virtually any external system — and with custom modules, you can extend that flexibility to cover business logic that standard endpoints don’t support. Whether you’re syncing inventory with an ERP or building a custom mobile experience, understanding how the Magento REST API works at both the configuration and code level puts you in full control.

If you’re planning a complex integration or need a custom Magento REST API module built to production standards, talk to our Magento development team to scope out your project.

Frequently Asked Questions

What Is the Magento REST API Used For?

The Magento REST API is used to integrate your store with external systems like ERPs, CRMs, mobile apps, and third-party logistics platforms. It supports CRUD operations on products, customers, orders, and categories through standard HTTP methods.

What Is the Difference Between Magento REST API and GraphQL?

The Magento 2 REST API returns fixed response structures and is best for back-end integrations. GraphQL lets you request only specific fields and is better suited for headless storefronts and PWA builds.

How Do I Authenticate With the Magento 2 REST API?

Generate an integration access token from System > Extensions > Integrations in the Magento admin. Pass the token in the Authorization: Bearer header on every API request.

How Do I Create a Custom Magento REST API Module?

You need four files: module.xml to register the module, webapi.xml to define the route, di.xml to map the interface to the model, and the model class implementing your logic. Run setup:upgrade after adding these files.

Can I Restrict Which Resources a Magento REST API Integration Can Access?

Yes. In the Admin Panel under Integrations, you select specific API resources when creating or editing an integration. In webapi.xml, you also set <resource ref=”…”/> to control which admin or customer roles can call each endpoint.

Is the Magento REST API Secure by Default?

Magento provides built-in authentication, but security depends on how you configure your integration. Use role-based access control, avoid anonymous endpoints for write operations, and validate all inputs in your custom modules.

About Author

Picture of Muhammad Bilal

Muhammad Bilal

Almost 10 Years of experience in web development and more specifically 7 years of experience in eCommerce on Magento platform. Core experties are PHP, MySql, Laraval, CodeIgniter, React, Knockout JS, Rest/Soap, graphQL & Magento 1&2 feature development and customizations

Table of Contents

Related Blogs

Magento Enterprise vs Shopify Plus: A Comprehensive 2026 Comparison for Ecommerce Growth
Magento

Magento Enterprise vs Shopify Plus: A Comprehensive 2026 Comparison for Ecommerce Growth

Choosing the wrong enterprise ecommerce platform can cost you months of migration work and hundreds of thousands in rework. For high-volume merchants weighing Magento Enterprise vs Shopify Plus, the decision is rarely straightforward — both platforms target enterprise buyers, but they serve fundamentally different business models. This guide breaks down the Shopify Plus vs Magento

Read More
Magento Dropshipping – A Complete Guide
Magento

Magento Dropshipping – A Complete Guide

You want to launch a dropshipping store without the overhead of managing inventory. Magento dropshipping makes that possible — but only if you understand how the platform works, which extensions to use, and where most new stores go wrong. This guide covers everything: how the dropshipping model works on Magento, how to set up your

Read More
Magento POS Integration: How to Integrate Magento with Your POS?
Magento

Magento POS Integration: How to Integrate Magento with Your POS?

Running both an online store and a physical retail location means you’re constantly juggling two separate systems — and every time inventory, pricing, or customer data gets out of sync, it costs you time, sales, and trust. A Magento POS integration solves exactly that by connecting your Magento store with your point of sale system

Read More