REST API / query on non-id db fields

When using “phx.gen.json” to generate a REST api, it doesn’t look like an api endpoint is created that allows retrieving data by querying on non-id database fields. My current need is to retrieve users by their email address. It looks like I need to modify my user controller and corresponding context method to get this functionality. Can someone confirm that this is what needs to be done? I would have guessed that this functionality would have been created out-of-the-box. I want to make sure that I’m not missing anything. Thanks

You are not missing anything.

The ID is the only canonical thing that the generators can assume to exist. But not every resource might have an email address.

Couldn’t you assume that all query-params on a get request were field name / value pairs and make the corresponding query?

You could, but do you really want to expose all fields of a table to the search? Perhaps some of those are very costly to search or just contain confidential information? Its easier to whitelist searchable fields after generating than blacklisting.

Simply because you’ll realize when you do not find records you do expect to find when you need to whitelist them, but you wont realize that you would find entries you do not be found because you wouldn’t try to find them until it happens either by accident or attack…

3 Likes

Yeah, good point, you wouldn’t want to create that functionality out-of-the-box in what gets created by phx.gen.json. That last sentence of yours was a doozy. Took 3 or 4 tries to unpack it. Thanks, much.