<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kim Forsgren on Medium]]></title>
        <description><![CDATA[Stories by Kim Forsgren on Medium]]></description>
        <link>https://medium.com/@kim_18277?source=rss-bd6702aaf4d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mL5PZgL4ffMYdp1IQ0Bh_g.jpeg</url>
            <title>Stories by Kim Forsgren on Medium</title>
            <link>https://medium.com/@kim_18277?source=rss-bd6702aaf4d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:01:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kim_18277/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Filter and Sort your API in Elixir and Phoenix - Part 1]]></title>
            <link>https://medium.com/ameglo/filter-and-sort-your-api-in-elixir-and-phoenix-part-1-9f69caee42b5?source=rss-bd6702aaf4d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f69caee42b5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[ecto]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[phoenix]]></category>
            <dc:creator><![CDATA[Kim Forsgren]]></dc:creator>
            <pubDate>Thu, 06 Apr 2017 06:32:02 GMT</pubDate>
            <atom:updated>2017-04-06T06:32:02.898Z</atom:updated>
            <content:encoded><![CDATA[<p>In this two part series we will cover filter and sorting your API in Elixir and Phoenix, starting with part 1, Filter.</p><p>Lets say that we have a resource Posts that our user can access in our API via the URL GET /api/posts and we would only want a subset of those posts. For example, only the Posts created by a user and date: GET /api/posts?created_by=user_id&amp;date=date.</p><p>To begin we have to define what we are allowed to filter on. We don’t want to be able to access all fields for security reasons.</p><p>This can be achieved with a plug:</p><pre>def valid_filters(conn, params) do<br>  filters = Enum.filter(conn.params, fn({k, v}) -&gt;<br>    Enum.member?(params, k)<br>  end)<br>  conn |&gt; assign(:filters, filters)<br>end</pre><p>and then used in the controller:</p><pre>defmodule MyApp.PostController do<br>  use MyApp.Web, :controller<br>  <br>  plug :valid_filters, ~w(created_by date) when action in [:index]</pre><pre>  def index(conn, _) do<br>    ...<br>  end<br>end</pre><p>This will create a Map in conn.assigns.filters containing only the allowed filter parameters, if they were provided.</p><p>For the next part we will be using Composable Queries, so if you are not familiar with the term I recommend this link to read more about it: <a href="https://blog.drewolson.org/composable-queries-ecto/">https://blog.drewolson.org/composable-queries-ecto/</a></p><p>Now we need to use these parameters we collected in the previous section and get the Posts we want. We will do this by creating a function in the Post model:</p><pre>def q_filtered_by(query, params) do<br>  Enum.reduce(params, query, fn({key, value}, query) -&gt;<br>    case String.downcase(key) do<br>      _ -&gt;<br>        from p in query,<br>        where: field(p, ^String.to_atom(key)) == ^value<br>    end<br>  end)<br>end</pre><p>This function will compose a query that only gets the Posts from the parameters provided, and we will use this combined with the parameters received by the plug</p><p><em>You may have noticed the redundant </em><em>case String.downcase(key) do, but we will get into this soon.</em></p><p>All we need to do now is use this function in our controller and we are all set:</p><pre>def index(conn, _) do<br>  posts = Post<br>    |&gt; Post.q_filtered_by(conn.assigns.filters)<br>    |&gt; Repo.all</pre><pre>  render(conn, &quot;index.json&quot;, posts: posts)<br>end</pre><p>This will work fine for most cases. However, every now and then we want to filter on something that requires a more advanced query than a simple equal check.</p><p>For example: We wants all posts that has at least one Comment.</p><p>Now we would have to extend our function q_filtered_by and thanks to that redundant line of code we added before, this is not a big issue. We can simply add this key in our case and write any query we want</p><pre>def q_filtered_by(query, params) do<br>  Enum.reduce(params, query, fn({key, value}, query) -&gt;<br>    case String.downcase(key) do<br>      &quot;has_comments&quot; -&gt;<br>        from p in query,<br>        left_join: c in assoc(p, :comments),<br>        having: count(c.id) &gt; 0,<br>        group_by: p.id<br>      _ -&gt;<br>        from p in query,<br>        where: field(p, ^String.to_atom(key)) == ^value<br>    end<br>  end)<br>end</pre><p>And that covers filter in Elixir and Phoenix.</p><p>In part 2 we will use what we have learned today and move on to sorting the result.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f69caee42b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ameglo/filter-and-sort-your-api-in-elixir-and-phoenix-part-1-9f69caee42b5">Filter and Sort your API in Elixir and Phoenix - Part 1</a> was originally published in <a href="https://medium.com/ameglo">Ameglo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>