J4.x

Adding an API to a Joomla Component/de: Difference between revisions

From Joomla! Documentation

Created page with "=== Gruppenfelder ==="
No edit summary
 
(17 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<noinclude><languages /></noinclude>
<noinclude><languages /></noinclude>
<noinclude>{{Joomla version|version=4.0}}</noinclude>
<noinclude>{{Joomla version|version=4.0}}</noinclude>
Diese Seite soll dokumentieren, wie sich die in {{jver|4.0}} eingeführte Webservices-Schicht in bestehende Joomla-Komponenten integrieren können. Dies setzt voraus, dass die Standard-Joomla-MVC-Schicht verwendet wird.
<span class="mw-translate-fuzzy">Diese Seite soll dokumentieren, wie sich die in {{jver|4.0}} eingeführte Webservices-Schicht in bestehende Joomla-Komponenten integrieren können. Dies setzt voraus, dass die Standard-Joomla-MVC-Schicht verwendet wird.</span>




Line 8: Line 8:
Repository der Erweiterung: https://github.com/joomla-extensions/weblinks
Repository der Erweiterung: https://github.com/joomla-extensions/weblinks


Pull request: https://github.com/joomla-extensions/weblinks/pull/407
<span lang="en" dir="ltr" class="mw-content-ltr">Pull request:</span> https://github.com/joomla-extensions/weblinks/pull/407


== Erster Schritt ==
<span class="mw-translate-fuzzy">== Zweiter Schritt ==</span>


1. Verzeichnis erstellen: '''''src/api'''''
<div lang="en" dir="ltr" class="mw-content-ltr">
The point of entry to your component from an API call is a plugin.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
The plugin re-routes the API call into the API code that services the request.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
In this example an API call to the weblinks component might be
</div>
<syntaxhighlight>
(<span lang="en" dir="ltr" class="mw-content-ltr">yourSite</span>)/api/index.php/v1/weblinks
</syntaxhighlight>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
This means your installation file is best represented as a package, pkg_weblinks in this case, so that it can contain not only your original component, but also the required plugin.
</div>
 
1. <span class="mw-translate-fuzzy">Verzeichnis erstellen:</span> '''''plugins/webservices/weblinks'''''.
 
<div lang="en" dir="ltr" class="mw-content-ltr">
Your plugin code goes in a subdirectory of the webservices directory under the plugins directory, in this example
</div> '''''plugins/webservices/weblinks'''''.
[[File:Struct2.png.png|500px|thumb|center|File system structure]]
 
2. <span class="mw-translate-fuzzy">In der Datei '''''weblinks.php''''', erstellen der Klasse:</span> '''''weblinks.php'''''<span lang="en" dir="ltr" class="mw-content-ltr">, create the class</span>  '''''PlgWebservicesWeblinks'''''.
 
<syntaxhighlight lang="php">
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Router\ApiRouter;
 
class PlgWebservicesWeblinks extends CMSPlugin
{
    public function onBeforeApiRoute(&$router)
    {
        $router->createCRUDRoutes('v1/weblinks', 'weblinks', ['component' => 'com_weblinks']);
    }
}
</syntaxhighlight>
 
<div class="mw-translate-fuzzy">
In der Methode '''''onBeforeApiRoute''''', alle Routen registrieren, die wir für den Webservice benötigen.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
When Joomla receives an API call it loads the API router which then collects a list of endpoints it should be aware of by running the ''onBeforeApiRoute'' method in all enabled plugin classes that contain it. Then it can locate the API component relevant to the API endpoint that has been called.
</div>
 
<span lang="en" dir="ltr" class="mw-content-ltr">The createCRUDRoutes method creates five routes; two GET routes for list and item data, and one POST, one PATCH, and one DELETE route. If you don't require this, simply create the routes directly here.</span>
 
<span class="mw-translate-fuzzy">== Erster Schritt ==</span>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
The router specifies the path for the relevant API code.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
This API code is in a folder named ''api'' off the site root. It is exactly analogous to the ''administrator'' and ''site'' sections.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
In your installation package this code should be included in your component installer because the Joomla installation process automatically creates a section for each installed component there, whether it has any API code or not.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
The structure of this section has the same directory pattern as the other extension sections (i.e. components, modules, plugins).
</div>
 
1. <span class="mw-translate-fuzzy">Verzeichnis erstellen:</span> '''''/api'''''.


[[File:Struct1.png|500px|thumb|center|File system structure]]
[[File:Struct1.png|500px|thumb|center|File system structure]]


2. Anlegen der Klasse: '''''WeblinksController'''''
2. <span class="mw-translate-fuzzy">Anlegen der Klasse:</span> '''''WeblinksController'''''.
<source lang="php">
 
<div lang="en" dir="ltr" class="mw-content-ltr">
The controller is named in the second parameter of the ''createCRUDRoutes'' method in the plugin.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
You can expose more than one output structure by registering more than one route, specifying a different controller for each structure.
</div>
 
<syntaxhighlight lang="php">
use Joomla\CMS\MVC\Controller\ApiController;
use Joomla\CMS\MVC\Controller\ApiController;


class WeblinksController extends ApiController  
class WeblinksController extends ApiController
{
{
     protected $contentType = 'weblinks';
     protected $contentType = 'weblinks';
Line 26: Line 104:
     protected $default_view = 'weblinks';
     protected $default_view = 'weblinks';
}
}
</source>
</syntaxhighlight>


Die folgenden Felder übersteuern (override):
Die folgenden Felder übersteuern (override):


  $contentType - wird als Standard für $modelName verwendet, wenn die Antwort als Typ-Objekt ausgegeben wird
  $contentType - <span class="mw-translate-fuzzy">wird als Standard für $modelName verwendet, wenn die Antwort als Typ-Objekt ausgegeben wird</span> $modelName <span lang="en" dir="ltr" class="mw-content-ltr">as well as when outputting response as type object</span>
  $default_view - wird als Standard für $viewName verwendet
  $default_view - <span class="mw-translate-fuzzy">wird als Standard für $viewName verwendet</span> $viewName
 
3. <span class="mw-translate-fuzzy">Anlegen der Klasse:</span> '''''JsonapiView.php'''''
 
<div lang="en" dir="ltr" class="mw-content-ltr">
Extending JsonApiView gives you the same kinds of features that HtmlView does in a usual component view, slightly changed to be appropriate for outputting JSON.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
'''Note''' Although the core class is JsonApiView (uppercase ''A'' for Api), your override must have a lowercase ''a''.
</div>


3. Anlegen der Klasse: '''''JsonApiView.php'''''
<div lang="en" dir="ltr" class="mw-content-ltr">
The item and list fields to render, as shown below, specify which fields to include in the respective outputs.
</div>


<source lang="php">
<syntaxhighlight lang="php">
use Joomla\CMS\MVC\View\JsonApiView as BaseApiView;
use Joomla\CMS\MVC\View\JsonApiView as BaseApiView;


class JsonApiView extends BaseApiView
class JsonapiView extends BaseApiView
{
{
     protected $fieldsToRenderItem = [
     protected $fieldsToRenderItem = [
Line 56: Line 146:
     ];
     ];
}
}
</source>
</syntaxhighlight>


Die folgenden Felder übersteuern (override):
Die folgenden Felder übersteuern (override):
Line 63: Line 153:
  $fieldsToRenderList - Array aus Feldern um Objekte aufzulisten
  $fieldsToRenderList - Array aus Feldern um Objekte aufzulisten


== Zweiter Schritt ==
<span lang="en" dir="ltr" class="mw-content-ltr">Notice that this indicates a significant difference between JSON API views and HTML views. With HTML views you are used to having separate files and directories for displaying a list of items and displaying individual items. There isn't the same "display" difference for JSON, so one JsonapiView handles both types. That's why both fields lists are both shown in this one view file.</span>
 
1. Verzeichnis erstellen: '''''plugins/webservices/weblinks'''''
 
[[File:Struct2.png.png|500px|thumb|center|File system structure]]
 
2. In der Datei '''''weblinks.php''''', erstellen der Klasse: '''''PlgWebservicesWeblinks'''''
<source lang="php">
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Router\ApiRouter;
 
class PlgWebservicesWeblinks extends CMSPlugin
{
    public function onBeforeApiRoute(&$router)
    {
        $router->createCRUDRoutes('v1/weblinks', 'weblinks', ['component' => 'com_weblinks']);
    }
}
</source>
 
In der Methode '''''onBeforeApiRoute''''', alle Routen registrieren, die wir für den Webservice benötigen.


3. Erstellen von: '''''weblinks.xml'''''
3. <span class="mw-translate-fuzzy">Erstellen von:</span>  '''''weblinks.xml'''''
<source lang="xml">
<syntaxhighlight lang="xml">
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="webservices" method="upgrade">
<extension version="3.1" type="plugin" group="webservices" method="upgrade">
     <name>plg_webservices_weblinks</name>
     <name>PLG_WEBSERVICES_WEBLINKS</name>
     <author>Joomla! Project</author>
     <author>Joomla! Project</author>
     <creationDate>August 2017</creationDate>
     <creationDate>August 2017</creationDate>
Line 105: Line 175:
     </languages>
     </languages>
</extension>
</extension>
</source>
</syntaxhighlight>


4. Erstellen der Dateien '''''en-GB/en-GB.plg_webservices_weblinks.ini''''', '''''en-GB/en-GB.plg_webservices_weblinks.sys.ini''''' mit dem folgenden Inhalt:
4. <span class="mw-translate-fuzzy">Erstellen der Dateien</span> <span class="mw-translate-fuzzy">mit dem folgenden Inhalt:</span>
<source lang="php">
 
<span lang="en" dir="ltr" class="mw-content-ltr">As usual, language files can, and should, be supplied;</span> '''''en-GB/plg_webservices_weblinks.ini''''', '''''en-GB/plg_webservices_weblinks.sys.ini'''''<span lang="en" dir="ltr" class="mw-content-ltr">. It may be unnecessary to provide the user language file (''.ini''), but content for the system file (''.sys.ini'') is required, if only for the plugin administration list.</span>
 
<syntaxhighlight lang="php">
; Joomla! Project
; Joomla! Project
; Copyright (C) 2005 - 2019 Open Source Matters. All rights reserved.
; Copyright (C) 2005 - 2019 Open Source Matters. All rights reserved.
Line 115: Line 188:


PLG_WEBSERVICES_WEBLINKS="Web Services - Weblinks"
PLG_WEBSERVICES_WEBLINKS="Web Services - Weblinks"
PLG_WEBSERVICES_WEBLINKS_XML_DESCRIPTION="Used to add weblinks routes to the Web Services API for your website."
PLG_WEBSERVICES_WEBLINKS_XML_DESCRIPTION="Used to add Web links routes to the Web Services API for your website."
</source>
</syntaxhighlight>


== Dritter Schritt ==
== Paketierung ==
1. In der Datei '''''src/administrator/components/com_weblinks/weblinks.xml''''' eine Beschreibung für die Webdienst-API-Dateien hinzufügen.
<span lang="en" dir="ltr" class="mw-content-ltr">There are two considerations for packaging, the code in the API section and the plugin.</span>
<source lang="xml">
<span lang="en" dir="ltr" class="mw-content-ltr">=== Component Packaging ===</span>
<span lang="en" dir="ltr" class="mw-content-ltr">As mentioned elsewhere, the API code is packaged with the component code. To include the code in the package, add the following section to your component manifest</span>
<syntaxhighlight lang="xml">
<api>
<api>
     <files folder="api/components/com_weblinks">
     <files folder="api">
      ##API_COMPONENT_FILES##
        <folder>src</folder>
     </files>
     </files>
</api>
</api></syntaxhighlight>
</source>
<span lang="en" dir="ltr" class="mw-content-ltr">This will create a section for your API code in the correctly named (for your component) folder under the ''api'' folder.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">=== Plugin Packaging ===</span>
<span class="mw-translate-fuzzy">Wenn dieses Plugin mit einem anderen Element (z. B. einer Komponente) verknüpft ist, dann muss das Ganze als Paket zusammengestellt werden.  In diesem Fall in der Datei</span>
<syntaxhighlight lang="xml">
<?xml version="1.0" encoding="utf-8"?>
<!--~
  ~ @package Weblinks
    ....
  -->


2. In der Datei  '''''src/administrator/manifests/packages/pkg_weblinks.xml''''' eine Beschreibung für das Webservice-Plugin hinzufügen.
<extension version="4.0.0" type="package" method="upgrade">
<source lang="xml">
    <name>Weblinks</name>
<files>
    <packagename>weblinks</packagename>
    ...
    <version>x.y.z</version>
    <file type="plugin" id="weblinks" group="webservices">plg_webservices_weblinks.zip</file>
    <!-- etc etc -->
</files>
 
</source>
    <!-- List of extensions to install -->
    <files>
        <!-- Component -->
        <file type="component" id="com_weblinks">com_weblinks.zip</file>
 
        <!-- Plugins: web services -->
        <file type="plugin" id="weblinks" group="webservices">plg_webservices_weblinks.zip</file>
    </files>
</extension>
</syntaxhighlight>


== Categories ==
== Kategorien ==  
1. Add categories support for weblinks webservice. Edit the file '''''src/plugins/webservices/weblinks/weblinks.php'''''
1. <span class="mw-translate-fuzzy">Hinzufügen der Kategorie-Unterstützung für den Weblinks-Webservice. Bearbeiten der Datei '''''src/plugins/webservices/weblinks/weblinks.php'''''.</span>
<source lang="php">
<syntaxhighlight lang="php">
class PlgWebservicesWeblinks extends CMSPlugin
class PlgWebservicesWeblinks extends CMSPlugin
{
{
Line 151: Line 243:
     }
     }
}
}
</source>
</syntaxhighlight>


Die Kategorie-Unterstützung für den Weblinks-Webservice hinzufügen. Bearbeiten der Datei: => 'com_weblinks'
<span class="mw-translate-fuzzy">Wir verwenden die vorgefertigte Komponente '''''com_categories''''' und müssen nur noch den Parameter</span> 'extension' => 'com_weblinks'


== Felder ==
<span class="mw-translate-fuzzy">== Felder ==</span>
1. Hinzufügen von Feldern und Feldgruppen für den Webservice „Weblinks“. Bearbeiten der Datei '''''src/plugins/webservices/weblinks/weblinks.php'''''
1. <span class="mw-translate-fuzzy">Hinzufügen von Feldern und Feldgruppen für den Webservice „Weblinks“. Bearbeiten der Datei</span> '''''src/plugins/webservices/weblinks/weblinks.php'''''
<source lang="php">
<syntaxhighlight lang="php">
class PlgWebservicesWeblinks extends CMSPlugin
class PlgWebservicesWeblinks extends CMSPlugin
{
{
Line 176: Line 268:
     }
     }
}
}
</source>
</syntaxhighlight>


2. Überschreiben der Funktion '''''save''''' in '''''WeblinksController'''''
2. Überschreiben der Funktion '''''save''''' in '''''WeblinksController'''''.
<source lang="php">
<syntaxhighlight lang="php">
class WeblinksController extends ApiController
class WeblinksController extends ApiController
{
{
Line 206: Line 298:
     ...
     ...
}
}
</source>
</syntaxhighlight>


3. Überschreiben der Funktionen '''''displayList, displayItem, prepareItem''''' in '''''Weblinks\JsonApiView'''''
3. Überschreiben der Funktionen '''''displayList, displayItem, prepareItem''''' in '''''Weblinks\JsonApiView'''''.


<source lang="php">
<syntaxhighlight lang="php">
class JsonApiView extends BaseApiView
class JsonApiView extends BaseApiView
{
{
Line 247: Line 339:
     ...
     ...
}
}
</source>
</syntaxhighlight>


In der Funktion ''prepareItem'' muss geachtet werden auf: <source lang="php">$field->apivalue</source> Falls der Typ des Feldes komplex ist, wird hoffentlich ein Wert für die Ausgabe in der Web Services API-Komponente zurückgegeben, andernfalls greifen wir zurück auf:  
<span class="mw-translate-fuzzy">In der Funktion ''prepareItem'' muss geachtet werden auf: <source lang="php">$field->apivalue</source> Falls der Typ des Feldes komplex ist, wird hoffentlich ein Wert für die Ausgabe in der Web Services API-Komponente zurückgegeben, andernfalls greifen wir zurück auf:</span>
<source lang="php">$field->rawvalue</source>
<syntaxhighlight lang="php">$field->rawvalue</syntaxhighlight>
 
<span lang="en" dir="ltr" class="mw-content-ltr">== Data ==</span>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
The core functionality renders the data that you would expect from a simple component in the normal web interface. For this, the API defaults to administration data models. However, providing a ''Model'' section in your API code gives you back the flexibility to construct whatever data shape you want just for your API output. Provide a model for each view with the usual naming conventions.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
The system JsonApiView class formats the JSON output as three data sets; links, items, and metadata. To change that, override the display class in your own JsonapiView and '''don't''' call the parent class.
</div>


== Beispiel für eine integrierte Arbeit ==
== Beispiel für eine integrierte Arbeit ==
'''''Hinweis: Nicht vergessen, das Weblinks Webservice Plugin zu aktivieren!'''''
'''''Hinweis: Nicht vergessen, das Weblinks Webservice Plugin zu aktivieren!'''''


=== Weblinks ===
<span class="mw-translate-fuzzy">=== Weblinks ===</span>
==== Liste von Weblinks erhalten ====
<span class="mw-translate-fuzzy">==== Liste von Weblinks erhalten ====</span>
curl -X GET /api/index.php/v1/weblinks
curl -X GET /api/index.php/v1/weblinks


Line 262: Line 364:
curl -X GET /api/index.php/v1/weblinks/{weblink_id}
curl -X GET /api/index.php/v1/weblinks/{weblink_id}


==== Weblink löschen ====
<span class="mw-translate-fuzzy">==== Weblink löschen ====</span>
curl -X DELETE /api/index.php/v1/weblinks/{weblink_id}
curl -X DELETE /api/index.php/v1/weblinks/{weblink_id}


==== Weblink erstellen ====
<span class="mw-translate-fuzzy">==== Weblink erstellen ====</span>
curl -X POST -H "Content-Type: application/json" /api/index.php/v1/weblinks -d  
<syntaxhighlight lang="javascript">
<source lang="javascript">
curl -X POST -H "Content-Type: application/json" /api/index.php/v1/weblinks -d
{
'{
     "access": "1",
     "access": "1",
     "alias": "",
     "alias": "",
Line 300: Line 402:
     "url": "http://somelink.com/",
     "url": "http://somelink.com/",
     "xreference": "xreference"
     "xreference": "xreference"
}
}'</syntaxhighlight>
</source>


==== Weblink aktualisieren ====
<span class="mw-translate-fuzzy">==== Weblink aktualisieren ====</span>
curl -X PUT -H "Content-Type: application/json" /api/index.php/v1/weblinks/{weblink_id} -d  
<syntaxhighlight lang="javascript">
<source lang="javascript">
curl -X PUT -H "Content-Type: application/json" /api/index.php/v1/weblinks/{weblink_id} -d
{
'{
     "catid": "8",
     "catid": "8",
     "description": "<p>some new text</p>",
     "description": "<p>some new text</p>",
Line 312: Line 413:
     "title": "new title",
     "title": "new title",
     "url": "http://newsomelink.com/"
     "url": "http://newsomelink.com/"
}
}'</syntaxhighlight>
</source>


=== Kategorien ===
=== Kategorien ===
Die Route zu den Weblinks-Kategorien ist: "v1/weblinks/categories"
<span class="mw-translate-fuzzy">Die Route zu den Weblinks-Kategorien ist:</span> ''v1/weblinks/categories''


Die Arbeitsweise ist vergleichbar mit: [[J4.x:Joomla_Core_APIs#Categories|Banners Categories]].
Die Arbeitsweise ist vergleichbar mit: [[S:MyLanguage/J4.x:Joomla_Core_APIs#Kategorien|Banner-Kategorien]].


== Felder ==
== Felder ==


Die Route zu den Weblinks-Feldern ist: "v1/fields/weblinks"
<span class="mw-translate-fuzzy">Die Route zu den Weblinks-Feldern ist:</span> ''v1/fields/weblinks''


Die Arbeitsweise ist vergleichbar mit: [[J4.x:Joomla_Core_APIs#Fields_Contact|Fields Contact]].
Die Arbeitsweise ist vergleichbar mit: [[S:MyLanguage/J4.x:Joomla_Core_APIs#Kontakt-Felder|Kontakt-Felder]].


=== Gruppenfelder ===
=== Gruppenfelder ===


Route Groups Fields Weblinks is: "v1/fields/groups/weblinks"
<span class="mw-translate-fuzzy">Die Route zu den Weblinks-Gruppenfeldern ist:</span> ''v1/fields/groups/weblinks''
 
Working with it is similar to [[J4.x:Joomla_Core_APIs#Groups_Fields_Contact|Groups Fields Contact]].


Die Arbeitsweise ist vergleichbar mit: [[S:MyLanguage/J4.x:Joomla_Core_APIs#Kontakt-Feldgruppen|Kontakt-Feldgruppen]]


<noinclude>
<noinclude>

Latest revision as of 11:36, 28 March 2024

Joomla! 
4.0

Diese Seite soll dokumentieren, wie sich die in Joomla 4.0 eingeführte Webservices-Schicht in bestehende Joomla-Komponenten integrieren können. Dies setzt voraus, dass die Standard-Joomla-MVC-Schicht verwendet wird.


Ein Beispiel der Webservices-Integration zur Erweiterung von Weblinks

Repository der Erweiterung: https://github.com/joomla-extensions/weblinks

Pull request: https://github.com/joomla-extensions/weblinks/pull/407

== Zweiter Schritt ==

The point of entry to your component from an API call is a plugin.

The plugin re-routes the API call into the API code that services the request.

In this example an API call to the weblinks component might be

(<span lang="en" dir="ltr" class="mw-content-ltr">yourSite</span>)/api/index.php/v1/weblinks

This means your installation file is best represented as a package, pkg_weblinks in this case, so that it can contain not only your original component, but also the required plugin.

1. Verzeichnis erstellen: plugins/webservices/weblinks.

Your plugin code goes in a subdirectory of the webservices directory under the plugins directory, in this example

plugins/webservices/weblinks.

File system structure

2. In der Datei weblinks.php, erstellen der Klasse: weblinks.php, create the class PlgWebservicesWeblinks.

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Router\ApiRouter;

class PlgWebservicesWeblinks extends CMSPlugin
{
    public function onBeforeApiRoute(&$router)
    {
        $router->createCRUDRoutes('v1/weblinks', 'weblinks', ['component' => 'com_weblinks']);
    }
}

In der Methode onBeforeApiRoute, alle Routen registrieren, die wir für den Webservice benötigen.

When Joomla receives an API call it loads the API router which then collects a list of endpoints it should be aware of by running the onBeforeApiRoute method in all enabled plugin classes that contain it. Then it can locate the API component relevant to the API endpoint that has been called.

The createCRUDRoutes method creates five routes; two GET routes for list and item data, and one POST, one PATCH, and one DELETE route. If you don't require this, simply create the routes directly here.

== Erster Schritt ==

The router specifies the path for the relevant API code.

This API code is in a folder named api off the site root. It is exactly analogous to the administrator and site sections.

In your installation package this code should be included in your component installer because the Joomla installation process automatically creates a section for each installed component there, whether it has any API code or not.

The structure of this section has the same directory pattern as the other extension sections (i.e. components, modules, plugins).

1. Verzeichnis erstellen: /api.

File system structure

2. Anlegen der Klasse: WeblinksController.

The controller is named in the second parameter of the createCRUDRoutes method in the plugin.

You can expose more than one output structure by registering more than one route, specifying a different controller for each structure.

use Joomla\CMS\MVC\Controller\ApiController;

class WeblinksController extends ApiController
{
    protected $contentType = 'weblinks';

    protected $default_view = 'weblinks';
}

Die folgenden Felder übersteuern (override):

$contentType - wird als Standard für $modelName verwendet, wenn die Antwort als Typ-Objekt ausgegeben wird $modelName as well as when outputting response as type object
$default_view - wird als Standard für $viewName verwendet $viewName

3. Anlegen der Klasse: JsonapiView.php

Extending JsonApiView gives you the same kinds of features that HtmlView does in a usual component view, slightly changed to be appropriate for outputting JSON.

Note Although the core class is JsonApiView (uppercase A for Api), your override must have a lowercase a.

The item and list fields to render, as shown below, specify which fields to include in the respective outputs.

use Joomla\CMS\MVC\View\JsonApiView as BaseApiView;

class JsonapiView extends BaseApiView
{
    protected $fieldsToRenderItem = [
        'id',
        'catid',
        'title',
        'alias',
        'url',
        'xreference',
        'tags',
    ];

    protected $fieldsToRenderList = [
        'id',
        'title',
        'alias',
    ];
}

Die folgenden Felder übersteuern (override):

$fieldsToRenderItem - Array aus Feldern zur Anzeige eines einzelnen Objekts
$fieldsToRenderList - Array aus Feldern um Objekte aufzulisten

Notice that this indicates a significant difference between JSON API views and HTML views. With HTML views you are used to having separate files and directories for displaying a list of items and displaying individual items. There isn't the same "display" difference for JSON, so one JsonapiView handles both types. That's why both fields lists are both shown in this one view file.

3. Erstellen von: weblinks.xml

<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="webservices" method="upgrade">
    <name>PLG_WEBSERVICES_WEBLINKS</name>
    <author>Joomla! Project</author>
    <creationDate>August 2017</creationDate>
    <copyright>(C) 2005 - 2019 Open Source Matters. All rights reserved.</copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
    <authorEmail>admin@joomla.org</authorEmail>
    <authorUrl>www.joomla.org</authorUrl>
    <version>4.0.0</version>
    <description>PLG_WEBSERVICES_WEBLINKS_XML_DESCRIPTION</description>
    <files>
         ##FILES##
    </files>
    <languages folder="administrator/language">
         ##LANGUAGE_FILES##
    </languages>
</extension>

4. Erstellen der Dateien mit dem folgenden Inhalt:

As usual, language files can, and should, be supplied; en-GB/plg_webservices_weblinks.ini, en-GB/plg_webservices_weblinks.sys.ini. It may be unnecessary to provide the user language file (.ini), but content for the system file (.sys.ini) is required, if only for the plugin administration list.

; Joomla! Project
; Copyright (C) 2005 - 2019 Open Source Matters. All rights reserved.
; License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php
; Note : All ini files need to be saved as UTF-8

PLG_WEBSERVICES_WEBLINKS="Web Services - Weblinks"
PLG_WEBSERVICES_WEBLINKS_XML_DESCRIPTION="Used to add Web links routes to the Web Services API for your website."

Paketierung

There are two considerations for packaging, the code in the API section and the plugin. === Component Packaging === As mentioned elsewhere, the API code is packaged with the component code. To include the code in the package, add the following section to your component manifest

<api>
    <files folder="api">
        <folder>src</folder>
    </files>
</api>

This will create a section for your API code in the correctly named (for your component) folder under the api folder. === Plugin Packaging === Wenn dieses Plugin mit einem anderen Element (z. B. einer Komponente) verknüpft ist, dann muss das Ganze als Paket zusammengestellt werden. In diesem Fall in der Datei

<?xml version="1.0" encoding="utf-8"?>
<!--~
  ~ @package Weblinks
    ....
  -->

<extension version="4.0.0" type="package" method="upgrade">
    <name>Weblinks</name>
    <packagename>weblinks</packagename>
    <version>x.y.z</version>
    <!-- etc etc -->

    <!-- List of extensions to install -->
    <files>
        <!-- Component -->
        <file type="component" id="com_weblinks">com_weblinks.zip</file>

        <!-- Plugins: web services -->
        <file type="plugin" id="weblinks" group="webservices">plg_webservices_weblinks.zip</file>
    </files>
</extension>

Kategorien

1. Hinzufügen der Kategorie-Unterstützung für den Weblinks-Webservice. Bearbeiten der Datei src/plugins/webservices/weblinks/weblinks.php.

class PlgWebservicesWeblinks extends CMSPlugin
{
    public function onBeforeApiRoute(&$router)
    {
        ...
        $router->createCRUDRoutes(
            'v1/weblinks/categories',
            'categories',
            ['component' => 'com_categories', 'extension' => 'com_weblinks']
        );
    }
}

Wir verwenden die vorgefertigte Komponente com_categories und müssen nur noch den Parameter 'extension' => 'com_weblinks'

== Felder == 1. Hinzufügen von Feldern und Feldgruppen für den Webservice „Weblinks“. Bearbeiten der Datei src/plugins/webservices/weblinks/weblinks.php

class PlgWebservicesWeblinks extends CMSPlugin
{
    public function onBeforeApiRoute(&$router)
    {
        ...
        $router->createCRUDRoutes(
            'v1/fields/weblinks',
            'fields',
            ['component' => 'com_fields', 'context' => 'com_weblinks.weblink']
        );

        $router->createCRUDRoutes(
            'v1/fields/groups/weblinks',
            'groups',
            ['component' => 'com_fields', 'context' => 'com_weblinks.weblink']
        );
    }
}

2. Überschreiben der Funktion save in WeblinksController.

class WeblinksController extends ApiController
{
    ...

    protected function save($recordKey = null)
    {
        $data = (array) json_decode($this->input->json->getRaw(), true);

        foreach (FieldsHelper::getFields('com_weblinks.weblink') as $field)
        {
            if (isset($data[$field->name]))
            {
                !isset($data['com_fields']) && $data['com_fields'] = [];

                $data['com_fields'][$field->name] = $data[$field->name];
                unset($data[$field->name]);
            }
        }

        $this->input->set('data', $data);

        return parent::save($recordKey);
    }

    ...
}

3. Überschreiben der Funktionen displayList, displayItem, prepareItem in Weblinks\JsonApiView.

class JsonApiView extends BaseApiView
{
    ...

    public function displayList(array $items = null)
    {
        foreach (FieldsHelper::getFields('com_weblinks.weblink') as $field)
        {
            $this->fieldsToRenderList[] = $field->name;
        }

        return parent::displayList();
    }

    public function displayItem($item = null)
    {
        foreach (FieldsHelper::getFields('com_weblinks.weblink') as $field)
        {
            $this->fieldsToRenderItem[] = $field->name;
        }

        return parent::displayItem();
    }

    protected function prepareItem($item)
    {
        foreach (FieldsHelper::getFields('com_weblinks.weblink', $item, true) as $field)
        {
            $item->{$field->name} = isset($field->apivalue) ? $field->apivalue : $field->rawvalue;
        }

        return parent::prepareItem($item);
    }

    ...
}
In der Funktion prepareItem muss geachtet werden auf:
$field->apivalue
Falls der Typ des Feldes komplex ist, wird hoffentlich ein Wert für die Ausgabe in der Web Services API-Komponente zurückgegeben, andernfalls greifen wir zurück auf:
$field->rawvalue

== Data ==

The core functionality renders the data that you would expect from a simple component in the normal web interface. For this, the API defaults to administration data models. However, providing a Model section in your API code gives you back the flexibility to construct whatever data shape you want just for your API output. Provide a model for each view with the usual naming conventions.

The system JsonApiView class formats the JSON output as three data sets; links, items, and metadata. To change that, override the display class in your own JsonapiView and don't call the parent class.

Beispiel für eine integrierte Arbeit

Hinweis: Nicht vergessen, das Weblinks Webservice Plugin zu aktivieren!

=== Weblinks === ==== Liste von Weblinks erhalten ==== curl -X GET /api/index.php/v1/weblinks

Einzelnen Weblink erhalten

curl -X GET /api/index.php/v1/weblinks/{weblink_id}

==== Weblink löschen ==== curl -X DELETE /api/index.php/v1/weblinks/{weblink_id}

==== Weblink erstellen ====

curl -X POST -H "Content-Type: application/json" /api/index.php/v1/weblinks -d
'{
    "access": "1",
    "alias": "",
    "catid": "8",
    "description": "<p>text</p>",
    "images": {
        "float_first": "",
        "float_second": "",
        "image_first": "",
        "image_first_alt": "",
        "image_first_caption": "",
        "image_second": "",
        "image_second_alt": "",
        "image_second_caption": ""
    },
    "language": "*",
    "metadata": {
        "rights": "",
        "robots": ""
    },
    "metadesc": "",
    "metakey": "",
    "modified": "",
    "params": {
        "count_clicks": "",
        "height": "",
        "target": "",
        "width": ""
    },
    "title": "weblink title",
    "url": "http://somelink.com/",
    "xreference": "xreference"
}'

==== Weblink aktualisieren ====

curl -X PUT -H "Content-Type: application/json" /api/index.php/v1/weblinks/{weblink_id} -d
'{
    "catid": "8",
    "description": "<p>some new text</p>",
    "language": "*",
    "title": "new title",
    "url": "http://newsomelink.com/"
}'

Kategorien

Die Route zu den Weblinks-Kategorien ist: v1/weblinks/categories

Die Arbeitsweise ist vergleichbar mit: Banner-Kategorien.

Felder

Die Route zu den Weblinks-Feldern ist: v1/fields/weblinks

Die Arbeitsweise ist vergleichbar mit: Kontakt-Felder.

Gruppenfelder

Die Route zu den Weblinks-Gruppenfeldern ist: v1/fields/groups/weblinks

Die Arbeitsweise ist vergleichbar mit: Kontakt-Feldgruppen