How to use Service API in Shopware 6?

Carmella Blick
2 min readDec 27, 2019

In this article, we will look into the module which can inject Service API in Shopware 6.

Overview

The main entry point for this purpose is the plugin’s main.js file. It has to be placed into the <plugin root>/src/Resources/app/administration/src the directory in order to be automatically found by Shopware 6.

Creating a service

Firstly, You have to create a service file in <plugin root>/src/Resources/app/administration/src /core/service/api .
In my case file name is test-api.service.js.
To learn more about service, there is a link.

import ApiService from 'src/core/service/api.service'; class TestService extends ApiService { constructor(httpClient, loginService, apiEndpoint = 'test') { super(httpClient, loginService, apiEndpoint); } saveConfig(config) { const apiRoute = `${this.getApiBasePath()}/save/config` return this.httpClient.post( apiRoute, { config: config }, { headers: this.getBasicHeaders() } ).then((response) => { return ApiService.handleResponse(response); }); } } export default TestService;

Import Service API file and then create a class of your service. In saveConfig function, ${this.getApiBasePath()} is a base path and this.getBasicHeaders() is a header of the request and apiRoute is a path of API controller as described in the above example.

To init this service class, a new script is placed at <plugin root>/src/Resources/app/administration/src /init/api-service.init.js.

See below the code example-

const Application = Shopware.Application; import TestService from '../../src/core/service/api/test-api.service'; Application.addServiceProvider('TestService', (container) => { const initContainer = Application.getContainer('init'); return new TestService(initContainer.httpClient, container.loginService); });

Service Injection

Service is injected into a Vue StoreFront Headless services component and can be referenced in the inject property:

inject: [ 'TestService' ] methods: { saveConfig { this.TestService.saveConfig(this.config); } }

Now you can use your service API in your Vue component.

I hope It will help you. Thanks

Originally published at https://webkul.com on December 27, 2019.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Carmella Blick
Carmella Blick

Written by Carmella Blick

A digital marketer helping business to discover the right digital marketing strategy. And sometimes a blogger who love to express views on popular market trends

No responses yet

Write a response