Giter VIP home page Giter VIP logo

headless's Introduction

TYPO3 Extension headless - JSON Content API for TYPO3 Headless solution

TYPO3 12 TYPO3 11 TYPO3 10 CI Status Latest Stable Version Total Downloads License Contributor Covenant Coverage Status

Headless

Headless allows you to render JSON from TYPO3 content. You can customize output by changing types, names and nesting of fields.

This extension provides backend part (JSON API) for TYPO3 PWA solution. Second part is a JavaScript application nuxt-typo3 which consumes JSON API and renders the content using Vue.js and Nuxt. See frontend documentation here: https://typo3-headless.github.io/nuxt-typo3/

If you have any questions just drop a line in #initiative-headless-pwa Slack channel.

URL
Repository: https://github.com/TYPO3-Headless/headless
Read online: https://docs.typo3.org/p/friendsoftypo3/headless/main/en-us/
TER: https://extensions.typo3.org/extension/headless/
Slack: https://typo3.slack.com/channels/initiative-headless-pwa

Features

  • JSON API for content elements
  • JSON API for page and meta data
  • JSON API for navigation, layouts
  • taking into account all language and translation configuration (e.g. fallback)
  • easily extendable with custom fields or custom content elements
  • custom data processors directly for headless usage
  • support for EXT:form
  • support for EXT:felogin
  • support for EXT:redirects
  • support for EXT:seo
  • [BETA] backend module for simulating page preview (with specific page type, lang, usergroup) see headless_dev_tools

Additional extensions and integrations

Requirements and compatibility

EXT:headless version TYPO3 support PHP support Status
>= 4.0 12 >= 8.1 Active development & support
>= 3.0 11 >= 7.4, <= 8.2 Active support
>= 2.0 9, 10 >= 7.2, <=7.4 Critical bugfixes only

Quickstart / Demo

If you want to take a look at working demo including frontend, backend and demo data, use our DDEV based demo project here: https://github.com/TYPO3-Initiatives/pwa-demo

Installation

Install extension using composer

composer require friendsoftypo3/headless

Documentation

Extension documentation

How to start with TYPO3 Headless video tutorial

Whether you are a developer, content manager, or a tech enthusiast, this tutorial is tailored to provide a comprehensive introduction to TYPO3 Headless, helping you to get started on your journey with confidence.

video still

Configuration

Since versions: 4.2 | 3.5 Flag headless is required to configure in site configuration!

This flag instructs how EXT:headless should behave in multisite instance.

For each site you can set in which mode site is operated (standard aka HTML response, headless, or mixed mode).

You can set headless flag manually in yaml file or via site configuration in the backend:

'headless': 0|1|2

Possible values:

While the legacy flag (true|false) is still recognized, transitioning to the integer notation is recommended.

  • 0 (formerly: false) = headless mode is deactivated for the site within the TYPO3 instance. Default value!
  • 1 (formerly: true) = headless mode is fully activated for the site within the TYPO3 instance.
  • 2 = mixed mode headless is activated (both fluid & json API are accessible within a single site in the TYPO3 instance).

Configuration steps

For a chosen site in TYPO3, follow these steps:

To enable Headless Mode:

  • In the typoscript template for the site, load the "Headless" setup file.
  • Set headless flag to a value of 1 in the site configuration file or configure the flag via editor in the Site's management backend.

To enable Mixed Mode:

  • In the typoscript template for the site, load the "Headless - Mixed mode JSON response" setup file instead of the default headless one.
  • Set headless flag to a value of 2 in the site configuration file or configure the flag via editor in the Site's management backend.

The mixed mode flag (value of 2) instructs the EXT:headless extension to additionally check for the Accept header with a value of application/json when processing requests to the particular site in the TYPO3 instance.

  • In cases where a request lacks the Accept header or Accept has a different value than application/json, TYPO3 will respond with HTML content (standard TYPO3's response).
  • In cases where a request's header Accept matches the value of application/json, TYPO3 will respond with a JSON response.

JSON Content Object

In headless extension we implemented new JSON Content Object, which allows you to specify what fields you want to output, and how they will look. First, let's take a look at simple example

lib.page = JSON
lib.page {
  fields {
    header = TEXT
    header {
      field = header
    }
  }
}

Output

{
    "header" : "headerFieldValue"
}

in addition, keyword fields allow you to nest multiple times fields in json, e.g.

lib.page = JSON
lib.page {
  fields {
    data {
      fields {
        foo = TEXT
        foo {
          field = bar
        }

        foo1 = TEXT
        foo1 {
          field = bar1
        }
      }
    }
  }
}

Output

{
    "data": [
        {
            "foo": "bar",
            "foo1": "bar1"
        }
    ]
}

INT, FLOAT & BOOL Content Objects for use in JSON Content Object

We introduce new simple content objects to improve JSON API response for frontend developers. We can set correct property types, so frontend does not have to deal with string values for fields with numeric values or field that should be true/false.

lib.page = JSON
lib.page {
  fields {
    data {
      fields {
        foo = INT
        foo {
          # db value of foo_field = 1
          field = foo_field
        }
        bar = BOOL
        bar {
          # db value of bar_field = 0
          field = bar_field
        }
      }
    }
  }
}

Output

{
    "data": [
        {
            "foo": 1,
            "bar": false
        }
    ]
}

Customizing

You can override every field in output using typoscript. This extension allows you to use standard typoscript objects such as TEXT, COA, CASE.

Example page response ⬇️

image

DataProcessing

You can use Data Processors just like in FLUIDTEMPLATE Content Object, e.g.

lib.languages = JSON
lib.languages {
  dataProcessing {
    10 = TYPO3\CMS\Frontend\DataProcessing\LanguageMenuProcessor
    10 {
      languages = auto
      as = languages
    }
  }
}

Built in data processors

We provide multiple data processors for headless rendering purposes.

DatabaseQueryProcessor

Used for fetching records from the database.

FilesProcessor

This processor should be used to process files (standard or media files).

Also, it allows you to process images. See docs chapter: Images for details.

GalleryProcessor

Should be used along with FilesProcessor (chained). Used for processing mutliple media files.

MenuProcessor

Used for navigation. Works just like standard menu processor.

FlexFormProcessor

Used for processing flexforms.

RootSitesProcessor

Render your all headless sites configuration for your frontend application.

Contributing

Alt

Development

Development for this extension is happening as part of the TYPO3 PWA initiative, see https://typo3.org/community/teams/typo3-development/initiatives/pwa/ If you have any questions, join the #initiative-headless-pwa Slack channel.

Credits

A special thanks goes to macopedia.com company, which is sponsoring development of this solution.

headless's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

headless's Issues

Outputting objects that implement \ArrayAccess

Hi,

I use a custom DataProcessor to output an object that implements \ArrayAccess. Currently it appears that such data will not be processed by the JSON-View (only if you convert the object to a plain php array).
I thinkt this would be a useful addition to allow for outputting objects that implement \ArrayAccess. What do you think?

Capability to customize the FriendsOfTYPO3\MenuProcessor TypoScript configuration

Unfortunately it seems not possible to customize the TypoScript configuration of FriendsOfTYPO3\MenuProcessor e.g. to append a new field "id": to the response. I need a unique value for each menu entry... and using the link value is hard to deal with because of type string.

Just out of curiosity I was trying this, but I guess this is not how the dataProcessing works in general^^

lib.primaryNavigation {
  dataProcessing {
    10 {
      stdWrap.cObject.100 = TEXT
      stdWrap.cObject.100 {
        field = uid
        wrap = "id":|
      }
    }
  }
}

Add extension to packagist

Hi everybody,
good work on the extension! :) Thanks for it.

But to make it easier to install the extension via composer it should be added to packagist.
Otherwise the extension can only be installed when the repo is added to the repositories array in composer.json.

Also a proper version tag should be added to the repo so we don't have to use dev-master when installing.

See error when installing it as discribed in the README:

Could not find a matching version of package friendsoftypo3/headless. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (stable)

best,
R

[Suggest] Use JSON:API standard

Instead of inventing an own JSON structure, please think about using the JSON:API standard that is widely supported by JS frameworks: https://jsonapi.org/

We have made good experience using the standard for our own JSON REST API for e-commerce:
https://github.com/aimeos/ai-admin-jqadm

A REST API also fits better than GraphQL for a CMS because a CMS frontend has to read a lot of data but don't need to write large data sets. We've published an article about the pros and cons of JSON:API and GraphQL: https://aimeos.org/tips/graphql-vs-jsonapi-for-ecommerce/

Dries from Drupal also made a good article why Drupal prefers JSON:API over GraphQL:
https://dri.es/headless-cms-rest-vs-jsonapi-vs-graphql

Get database records with custom JSON structure

Hi,
in our current project we have a custom content element where we can list pages by given page types (doktype). To get these pages we use a DatabaseQueryProcessor currently.
Now we want to use the headless extension and we we need a way to render this content element as JSON. The output should be something like:

...
{
    "content": {
        "pages": [
            {
                "id": 1,
                "pid": 0,
                ... SAME STRUCTURE AS "lib.page" FROM EXT:headless
            },
            { ... }
        ]
    }
}

Inside pages every page object should have the same structure as in lib.page.

Do you think it’s a good idea to write an own DatabaseQueryProcessor to get data from a specific table in a custom structure? Or is it better to use the CONTENT/RECORDS Content Objects for this (combined with the JSON Content Object)? And do you think this functionality should be added to EXT:headless?

best,
R

Set error handling output to JSON

Hi,
when adding a new error handling inside a site configuration and set the handler to "Show Content from Page", the output of this page is of type text/html; charset=utf-8 because the page TypoScript doesn't apply here.

In a project where we used our own headless extension before, we used a Middleware to set the Content-Type-Header always to application/json; charset=utf-8 for every request. This also would make the additionalHeaders part in PageConfiguration.typoscript and MenuConfiguration.typoscript redundant.

Is this something you consider having in this extension as well? I could open a pull request for this, but wanted to ask here first and to see what's your opinion on this.

This has to be tested very well for sure as I don't know yet what happens to Exceptions that occur after the new Middleware. Maybe they are also set to application/json. 🤔

Additionally we could extend the errorHandler selection with an option to also select a JSON file. Just like with the "Fluid Template" option.

What do you think?

best,
R

[FEATURE] Add non-cached plugin INT_SCRIPT handling

Find way to output non-cached plugin data. We can use typoscript rendering extension, but we want to solve this without additional prerequisites. Problem is that INT_SCRIPT is hardcoded in ContentObjectRenderer to have max 32 characters, but JsonContentObject wrap INT_SCRIPT in " ", so it's 34 character long. We can also hook into ContentObjectRenderer and clean INT_SCRIPT.

Typoscript for Shortcut seems to be invalid

After having troubles to add typoscript after headless was included I drilled it down to line #14 in Configuration/TypoScript/ContentElement/Shortcut.typoscript.

If I put it into anything conditional the BE complains about a missing brace. All following typoscript will land at unintended places.

Screenshot is attached to show the place where the error seems to be. (#2490 in that case)

styles.content.shortcut.tables is set to tt_content

image

Each page the same json-content?

Today i was testing the headless-extension but i failed at the very beginning...

Each page i call up, shows the same json-content (only navigation)
[{"data":{"uid":83,"pid":1,"tstamp":1571222872,"crdate":1571222872,"cruser_id":1,"deleted":0,"hidden":0,"starttime":0,"endtime":0,"fe_group":"","sorting":0,"rowDescription":null,"editlock":0,"sys_language_uid":0,"l10n_parent":0,"l10n_source":0,"l10n_state":null,"t3_origuid":0,"l10n_diffsource":"a:1:{s:8:\"shortcut\";N;}","t3ver_oid":0,"t3ver_id":0,"t3ver_label":"","t3ver_wsid":0,"t3ver_state":0,"t3ver_stage":0,"t3ver_count":0,"t3ver_tstamp":0,"t3ver_move_id":0,"perms_userid":1,"perms_groupid":1,"perms_user":31,"perms_group":27,"perms_everybody":0,"title":"Home","slug":"\/home","doktype":4,"TSconfig":"","is_siteroot":0,"php_tree_stop":0,"url":"","shortcut":1,"shortcut_mode":0,"subtitle":"","layout":0,"target":"","media":0,"lastUpdated":0,"keywords":"","cache_timeout":0,"cache_tags":"","newUntil":0,"description":"","no_search":0,"SYS_LASTCHANGED":0,"abstract":"","module":"","extendToSubpages":0,"author":"","author_email":"","nav_title":"","nav_hide":0,"content_from_pid":0,"mount_pid":0,"mount_pid_ol":0,"alias":"","l18n_cfg":0,"fe_login_mode":0,"backend_layout":"","backend_layout_next_level":"","tsconfig_includes":"","legacy_overlay_uid":0,"tx_impexp_origuid":54,"seo_title":"","no_index":0,"no_follow":0,"og_title":"","og_description":null,"og_image":0,"twitter_title":"","twitter_description":null,"twitter_image":0,"canonical_link":"","categories":0,"nav_icon":0,"thumbnail":0,"isSpacer":false},"title":"Home","link":"\/","target":"","active":0,"current":0,"spacer":0,"icon":[]},{"data":{"uid":82,"pid":1,"tstamp":1571222872,"crdate":1571222872,"cruser_id":1,"deleted":0,"hidden":0,"starttime":0,"endtime":0,"fe_group":"","sorting":1,"rowDescription":null,"editlock":0,"sys_language_uid":0,"l10n_parent":0,"l10n_source":0,"l10n_state":null,"t3_origuid":0,"l10n_diffsource":"a:1:{s:6:\"hidden\";N;}","t3ver_oid":0,"t3ver_id":0,"t3ver_label":"","t3ver_wsid":0,"t3ver_state":0,"t3ver_stage":0,"t3ver_count":0,"t3ver_tstamp":0,"t3ver_move_id":0,"perms_userid":1,"perms_groupid":1,"perms_user":31,"perms_group":31,"perms_everybody":0,"title":"Spacer","slug":"\/spacer","doktype":199,"TSconfig":null,"is_siteroot":0,"php_tree_stop":0,"url":"","shortcut":0,"shortcut_mode":0,"subtitle":"","layout":0,"target":"","media":0,"lastUpdated":0,"keywords":null,"cache_timeout":0,"cache_tags":"","newUntil":0,"description":null,"no_search":0,"SYS_LASTCHANGED":0,"abstract":null,"module":"","extendToSubpages":0,"author":"","author_email":"","nav_title":"","nav_hide":0,"content_from_pid":0, {...}

can anybody tell me, what i'm doin wrong?

kind regards / thx

Add version tag to Github and/or add branch-alias to composer.json

Hi guys,
sorry for opening so many issues. 🙈

Would it be possible to add a tag to the repo so we don’t have to checkout dev-master? Alternatively (or additionally 🙂) the branch-alias functionality of composer.json could be used.

for example:

"extra": {
    "branch-alias": {
      "dev-master": "1.0.x-dev"
    }
  }

So we could simply use ^1.0 in our own projects composer.json and don’t have to bother changing the version when v1.0 is finally released/a tag is created.

best,
Ramón

Add json fields

Hi,
there are some fields that are missing in my opinion.

In "lib.page":

  • files (array of objects): The files added to a page in "Resources -> Files"
  • socialMedia (object): The fields og_title, og_description, twitter_title, twitter_description, twitter_image combined.
  • noSearch (bool): The output of the field "Include in Search"
  • categories (array of objects): The categories the page is assigned to.

In "lib.contentElement":

  • categories (array of objects): The categories the content element is assigned to.

Is there a reason that these fields are missing or do you think they can be added as well? Because I think they are important for the frontend rendering.

[FEATURE] Using felogin authentication over headless API

Not sure if this is possible already out of the box, can you as developer say something to this? If it's not possible, this would be a good feature-resquest as the user management is one of the strength of TYPO3 over other systems in my opinion, which should work especially in web-apps.

Wrong MenuProcessor in MenuAbstract.typoscript

Hi,
the MenuProcessor used in Configuration/TypoScript/ContentElement/MenuPages.typoscript is TYPO3\CMS\Frontend\DataProcessing\MenuProcessor. But this outputs every single DB column of the page. This should probably be FriendsOfTYPO3\Headless\DataProcessing\MenuProcessor (like in the other menu content elements) to limit the fields that are displayed in the json.

But when changing the namespace the chained FilesProcessor is throwing an exception.

MenuProcessor is missing "data"

I needed sys_categories in my menu, so I tried to attach them to the MenuProcessor. The Problem is, that the MenuProcessor has no data object which passes the required fields back.

         ` menu = TEXT
            menu {
                dataProcessing {
                    10 = FriendsOfTYPO3\Headless\DataProcessing\MenuProcessor 
                    10 {
                        special = list
                        special.value.field = pages
                        as = menu
                        dataProcessing {
                            10 = FriendsOfTYPO3\Headless\DataProcessing\FilesProcessor
                            10 {
                                references.fieldName = menu_image
                                as = image
                                processingConfiguration.height = {$projects.image.height}
                                processingConfiguration.width = {$projects.image.width}
                            }
                            20 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor
                            20 {
                                as = categories
                                selectFields = sys_category.title
                                table = sys_category
                                pidInList = root,-1
                                where = sys_category_record_mm.uid_foreign = {field:uid}
                                where.insertData = 1
                                leftjoin = sys_category_record_mm ON sys_category_record_mm.uid_local = sys_category.uid
                            }
                        }
                    }
                }
            }`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.