<p>Yes, it is possible, I used to do this for simple tasks years ago, before the <a href="https://plugins.craftcms.com/element-api" rel="nofollow noreferrer">Element API</a> plugin was released, and now there is the <a href="https://craftcms.com/docs/3.x/graphql.html" rel="nofollow noreferrer">GraphQL API</a>, 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.</p>
<p>Here is a trivial example:</p>
<pre><code>{# 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() %} 
</code></pre>

CC BY-SA 4.0
2021-09-19T07:09:58.503Z
2021-09-19T07:09:58.503Z
Ben Croker
<p>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</p>

CC BY-SA 4.0
2021-09-18T11:22:49.407Z
2021-09-18T11:22:49.407Z
joomkit
<p>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.</p>
<p>Is it possible to develop API with TWIG template?</p>
<p>Thanks</p>

<templating><php><api>
How to develop API with TWIG
# How to develop API with TWIG

(Asked by: username_0 on 2021-01-22)

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?

Thanks

**Tags:** templating, php, api


---

## 2 answers

### Answer by username_1 on 2021-09-19. Score: 1

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() %}


---

### Answer by username_2 on 2021-09-18. Score: 0

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


---

