Skip to content
Piyush Dankhra
Go back

How does PWA Studio communicate with Magento?

Last updated:

There are two ways PWA Studio communicates with Magento 2:

  1. GraphQL
  2. REST API

To connect with Magento 2, it uses the MAGENTO_BACKEND_URL parameter of the .env file. It uses this specified Magento instance to fetch data.

#### Connecting to a Magento store #############################################
#
#   Connect to an instance of Magento 2.3 by specifying its public domain name.
MAGENTO_BACKEND_URL=https://magento.local/
#
################################################################################.env

Note: This is the base URL, not the Magento admin URL.

GraphQL

GraphQL is the main endpoint to read and manipulate data. PWA Studio uses Apollo Client to fetch data via GraphQL. With Apollo Client, queries can be cached for faster communication.

If we look under the src/index.js file in the Venia concept package:

ReactDOM.render(
    <Adapter apiBase={apiBase} apollo={{ link: apolloLink }} store={store}> {}
        <AppContextProvider>
            <App />
        </AppContextProvider>
    </Adapter>,
    document.getElementById('root')
);packages/venia-concept/src/index.js

File source: https://github.com/magento/pwa-studio/blob/develop/packages/venia-concept/src/index.js#L22

Inside components, you can use GraphQL queries to fetch and render data and mutations to write data back to Magento.

REST API

The second option available is the REST API. Most operations use GraphQL, but if there is no GraphQL endpoint available for a specific extension or functionality, you can fall back to the REST API.

For example, PWA Studio uses the Peregrine REST API helpers to POST shipping and payment information in the submitOrder call.

If we look inside the asyncActions.js file:

import { Magento2 } from '../../../RestApi';
const { request } = Magento2;packages/peregrine/lib/store/actions/checkout/asyncActions.js

It then uses request to POST data inside the submitOrder function using the REST API:

// POST to shipping-information to submit the shipping address and shipping method.
const guestShippingEndpoint = `/rest/V1/guest-carts/${cartId}/shipping-information`;
const authedShippingEndpoint =
    '/rest/V1/carts/mine/shipping-information';
const shippingEndpoint = user.isSignedIn
    ? authedShippingEndpoint
    : guestShippingEndpoint;

await request(shippingEndpoint, {
    method: 'POST',
    body: JSON.stringify({
        addressInformation: {
            billing_address,
            shipping_address,
            shipping_carrier_code: shipping_method.carrier_code,
            shipping_method_code: shipping_method.method_code
        }
    })
});packages/peregrine/lib/store/actions/checkout/asyncActions.js

In summary:


Share this post on:

Previous Post
How to deploy the PWA Studio project to the server using the UPWARD connector?
Next Post
What is the Magento PWA Studio?