Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom JSON-API resource drupal 8

Tags:

drupal

I have issues with creating custom JSON API resource which will be visible on mydrupalsite/jsonapi link. I have found this example:

https://glamanate.com/blog/using-json-api-query-your-search-api-indexes

which shows how to create custom resource but it is outdated. I tried to make a custom module looking in this article, but it doesn't work anymore because json-api module has changed.

For example, I want to show all nodes and make the jsonapi endpoint of type nodes--all which will serve all the nodes of my Drupal site.

I am using drupal 8.7.1 and JSON API core module.

I have tried to google this problem, but there are no examples for creating custom json api endpoints.

For final result i want to make jsonapi endpoint for example: mydrupalsite/jsonapi/nodes/all which will serve all nodes.

like image 816
Ivo Kovačević Avatar asked Sep 02 '25 13:09

Ivo Kovačević


2 Answers

You could declare REST endpoints within a custom module.

In /modules/custom/mymodule/src/Plugin/rest/resrouce/MyEndPoints.php, create a class extending ResourceBase, according to https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources.

Then you could define which set of nodes you want to expose, use query parameters to filter them, paginate, or do whatever you want.

See also : https://medium.com/@emerico/create-custom-rest-resource-for-get-and-post-method-in-drupal-8-e445330be3ff

I successfully used this technique to get events displayed with FullCalendar library, I can elaborate on this if it helps.

Good luck with it

like image 85
Florian Motteau Avatar answered Sep 04 '25 01:09

Florian Motteau


The module does not currently support external connection to its internal-use-only API according to the JSON:API's module maintainers, hence why your referenced module does not work anymore.

There are plans for the mixed bundle you are requesting. See the thread below for the discussion.

https://www.drupal.org/project/jsonapi_extras/issues/2956414

like image 45
briangonzalezmia Avatar answered Sep 04 '25 02:09

briangonzalezmia