2

Extremely not a PHP developer here but trying to set up a simple API with Element API. I've got the basics working to filter my entry results based off of a query URL parameter:

use craft\elements\Entry;

return [
    'endpoints' => [
        'recipes.json' => function() {
            $entryCriteria = [
                'section' => 'recipes'
            ];

            // filter by search query
            $searchQuery = Craft::$app->request->getQueryParam('query');
            if($searchQuery) {
                $entryCriteria += [
                    'search' => $searchQuery,
                    'orderBy' => 'score'
                ];
            }

            return [
                'elementType' => Entry::class,
                'elementsPerPage' => 12,
                'criteria' => $entryCriteria,
                'transformer' => function(Entry $entry) {
                    return [
                        'id' => $entry->id,
                        'title' => $entry->title,
                        'uri' => $entry->uri,
                        'recipeImg' => $entry->recipeImg->one()->url
                    ];
                },
                'pretty' => true
            ];
        }
    ]
];

I'm guessing getQueryParam() doesn't escape the returned data by default, and I would assume it's a good idea to do so before passing it into the plugin, but I don't know how to do that. I assume Craft has a built-in function for that but I don't know what it is or how to use it!

1 Answer 1

3

You don't need to escape the parameter, that's done by the element query for you. Passing the parameter directly will allow your users to use search syntax in the search term, but won't present a security issue.

2
  • 2
    Worth noting that the search syntax can allow users to filter by information that is otherwise not public—for example, if a site allowed accountholders to publish (and search by) biographical information… email:"august domain com" might make it easier to surmise login info; or localChapterZipCode:123* could expose users’ general geographic location. Of course, this is a pretty limited attack surface, as the user would have to know what your fields’ and attributes’ handles are, understand keyword normalization, scoring, etc. Nov 7 at 18:53
  • @AugustMiller Good point! Any best practice to preventing this leak? I.e. is there a way to disallow search syntax when passing user terms?
    – MoritzLost
    Nov 8 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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