I want to develop an API within Twig template that will have PDO implementation to get data. My application will be using content through CRAFT.

Is it possible to develop API with TWIG template?



Yes, it is possible, I used to do this for simple tasks years ago, before the Element API plugin was released, and now there is the GraphQL API, of course. But it really only is practical for pre-determined queries, otherwise you should probably use one of the solutions above or a custom module/plugin.

Here is a trivial example:

{# Fetches entries with specific custom field values. #}

{# Get initial entry query. #}
{% set entryQuery = craft.entries %}

{# Get custom field values from query params. #}
{% set params = craft.app.request.queryParams %}

{# Filter entries by custom field values. #}
{% if params.customField1 is defined %}
    {% do entryQuery.customField1(params.customField1) %}
{% endif %}

{# ... #}

{# Output the entries. #}
{% set entries = entryQuery.all() %} 

I think you'd need to do this in a plugin. You might call an API from twig with js for a one or two queries but a full crud operation probably isn't suitable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.