<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sebastian G. Vinci</title>
    <description>The latest articles on DEV Community by Sebastian G. Vinci (@svinci).</description>
    <link>https://dev.to/svinci</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F9589%2F5090903.jpeg</url>
      <title>DEV Community: Sebastian G. Vinci</title>
      <link>https://dev.to/svinci</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/svinci"/>
    <language>en</language>
    <item>
      <title>Python decorators in a nutshell.</title>
      <dc:creator>Sebastian G. Vinci</dc:creator>
      <pubDate>Wed, 06 Feb 2019 02:35:58 +0000</pubDate>
      <link>https://dev.to/svinci/python-decorators-in-a-nutshell-5bnf</link>
      <guid>https://dev.to/svinci/python-decorators-in-a-nutshell-5bnf</guid>
      <description>&lt;h2&gt;
  
  
  What's a decorator anyway?
&lt;/h2&gt;

&lt;p&gt;Decorators are a way to extend the behavior of pieces of software without actually having to modify them.&lt;/p&gt;

&lt;p&gt;In Python, in particular, they are functions that can change the behavior of other functions without changing their code. They provide a transparent way of adding satelital functionalities to already defined functions.&lt;/p&gt;

&lt;p&gt;For example, imagine we want to measure the time it takes to execute a couple functions in our program. We could code a timer around their behavior by modifying them all, &lt;strong&gt;or&lt;/strong&gt; we can create a decorator, centralizing the logic of timing a function within one place and applying it to several functions.&lt;/p&gt;

&lt;h2&gt;
  
  
  A couple concepts we need to know first...
&lt;/h2&gt;

&lt;h3&gt;
  
  
  In Python, functions are first-class objects.
&lt;/h3&gt;

&lt;p&gt;This means that functions can be assigned to variables and parameters, and even be returned by other functions.&lt;/p&gt;

&lt;p&gt;Functions that return other functions, or that receive other functions as arguments, are called higher order functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def prepare_hello(name: str):
    def say_hello():
        print("Hello, {}!".format(name))
    return say_hello

hello_brian = prepare_hello("Brian")
hello_brian()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;On the above snippet, &lt;code&gt;prepare_hello&lt;/code&gt; is a higher order function, as it returns another function. Also, we can see how we can assign functions to variables, as &lt;code&gt;hello_brian&lt;/code&gt; is a variable that holds the function returned by &lt;code&gt;prepare_hello&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A couple known higher order functions in Python are &lt;code&gt;map&lt;/code&gt;, &lt;code&gt;filter&lt;/code&gt;, &lt;code&gt;sort&lt;/code&gt; and &lt;code&gt;reduce&lt;/code&gt;. These are functions that receive a collection &lt;em&gt;and a function&lt;/em&gt;  as argument, to let us process the collection using the given function in different ways.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;*args&lt;/code&gt; and &lt;code&gt;**kwargs&lt;/code&gt;.
&lt;/h3&gt;

&lt;p&gt;You may already know these guys, they are pretty famous around Python. Both &lt;code&gt;*args&lt;/code&gt; and &lt;code&gt;**kwargs&lt;/code&gt; allow you to pass a variable number of arguments to a function. Your function is basically a blank check if the signature contains one or both of these guys.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def blank_check(*args, **kwargs):
    for arg in args:
        print("Arg: {}".format(arg))
    for keyword, arg in kwargs.items():
        print("Kw: {}, Arg: {}".format(keyword, arg))

blank_check(1, 2, 3, hello="Hello", word="World")
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here's the output of the above function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Arg: 1
Arg: 2
Arg: 3
Kw: hello, Arg: Hello
Kw: word, Arg: World
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As you can see, arguments passed without a keyword are handled by &lt;code&gt;*args&lt;/code&gt;, and arguments passed with a keyword are handled by &lt;code&gt;**kwargs&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This allows us to write functions that do not care at all about the arguments they receive, which will make a hell of a lot easier to write versatile decorators.&lt;/p&gt;

&lt;p&gt;A thing to notice is that the important part of &lt;code&gt;*args&lt;/code&gt; and &lt;code&gt;**kwargs&lt;/code&gt; are the aesterisks. The name can be anything, as any other variable, &lt;code&gt;args&lt;/code&gt; and &lt;code&gt;kwargs&lt;/code&gt; are used by convention, as this practice is dark-ish and needs to be spotted right away.&lt;/p&gt;

&lt;h2&gt;
  
  
  Now, decorators!
&lt;/h2&gt;

&lt;p&gt;Decorators are, basically, functions that wrap other functions. In Python it really is as easy as that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def a_decorator(wrapped_function):
    def wrapper(*args, **kwargs):
        print('I am the decorator!')
        return wrapped_function(*args, **kwargs)
    return wrapper
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That's the definition of a decorator, right there. You can see two interesting things there:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The decorator receives the function it is supposed to wrap as an argument, &lt;strong&gt;and&lt;/strong&gt; returns a wrapper function. Therefore, a decorator is a higher order function.&lt;/li&gt;
&lt;li&gt;The decorator, by using &lt;code&gt;*args&lt;/code&gt; and &lt;code&gt;**kwargs&lt;/code&gt;, does not care &lt;strong&gt;at all&lt;/strong&gt; what are the arguments of the wrapped function, it just does its thing and calls the wrapped function with all the given arguments.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, we can use it wherever we want:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@a_decorator
def sum_numbers(num_a, num_b):
    return num_a + num_b

print(sum_numbers(1, 2))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The output will be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;I am the decorator!
3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;It is really transparent, see? And although it is pretty magical, it is really explicit. You go to the definition of the function and you see right there, in your face, what decorators are being executed.&lt;/p&gt;

&lt;p&gt;This implementation, though, has a subtle issue:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(sum_numbers.__name__)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That will print out &lt;code&gt;wrapper&lt;/code&gt;, as that's the name of the &lt;code&gt;wrapper&lt;/code&gt; function the decorator returns. Now, when debugging, that thing right there will be a pain in the butt. But we can fix it! And we can fix it with the standard library! :D&lt;/p&gt;

&lt;p&gt;There is a module in python called &lt;code&gt;functools&lt;/code&gt; that provides a lot of awesome things to work with functions. I really encourage you to go and see what it has to offer, but today we are just going to use one decorator it provides.&lt;/p&gt;

&lt;p&gt;The decorator &lt;code&gt;functools.wraps&lt;/code&gt; receives a function as argument and basically overrides the wrapped function properties with the ones of the given function.&lt;/p&gt;

&lt;p&gt;Let's change our decorator using &lt;code&gt;functools.wraps&lt;/code&gt; to see this in action.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from functools import wraps

def a_decorator(wrapped_function):
    @wraps(wrapped_function)
    def wrapper(*args, **kwargs):
        print('I am the decorator!')
        return wrapped_function(*args, **kwargs)
    return wrapper

@a_decorator
def sum_numbers(num_a, num_b):
    return num_a + num_b

print(sum_numbers.__name__)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That will print &lt;code&gt;sum_numbers&lt;/code&gt; again, fixing our issue elegantly. Now, how come &lt;code&gt;wraps&lt;/code&gt; receives parameters? How do I do that? You'll need an intermediate function that receives those parameters and returns the wrapper function.&lt;/p&gt;

&lt;p&gt;Your decorator will not actually be a decorator, it will be a decorator &lt;em&gt;builder&lt;/em&gt;, which receives a couple of arguments and returns a decorator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def a_decorator(name):
    def actual_decorator(wrapped_function):
        @wraps(wrapped_function)
        def wrapper(*args, **kwargs):
            print('I am the decorator, {}!'.format(name))
            return wrapped_function(*args, **kwargs)
        return wrapper
    return actual_decorator

@a_decorator("Sum Numbers")
def sum_numbers(num_a, num_b):
    return num_a + num_b

print(sum_numbers(1, 2))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  The actual problem we wanted to solve
&lt;/h2&gt;

&lt;p&gt;Let's say, we have a function we want to time:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def fibonacci(n, a = 0, b = 1):
    if n == 0: 
        return a 
    if n == 1: 
        return b 
    return fibonacci(n - 1, b, a + b)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, let's just drop the idea of adding timing functionality directly to it, as it would pollute its code, making it more complex to follow, just because we wanted to add non-critical behavior to it.&lt;/p&gt;

&lt;p&gt;So, let's write a decorator called &lt;code&gt;timer&lt;/code&gt; that receives a cool operation name (to make it more readable in the logs) and add &lt;code&gt;@timer("Fibonacci calculator")&lt;/code&gt; to the original function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from datetime import datetime
from functools import wraps

def timer(operation_name):
        def timer_decorator(wrapped_function):
                @wraps(wrapped_function)
                def wrapper(*args, **kwargs):
                        start = datetime.now()
                        result = wrapped_function(*args, **kwargs)
                        end = datetime.now()
                        print("{} took {}.".format(operation_name, end - start))
                        return result
                return wrapper
        return timer_decorator

@timer("Fibonacci calculator")
def fibonacci(n, a = 0, b = 1):
    if n == 0:
        return a
    if n == 1:
        return b
    return fibonacci(n - 1, b, a + b)

fibonacci(30)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, in the output we'll see how much time each execution of fibonacci took, taking into account it is a recursive function and for &lt;code&gt;n=30&lt;/code&gt; it will execute itself 30 times. So we'll see in the output &lt;code&gt;Fibonacci calculator took &amp;lt;time&amp;gt;&lt;/code&gt; thirty times.&lt;/p&gt;

&lt;p&gt;This experiment also makes it very clear that Python doesn't do tail recursion optimization, so keep that one in mind :P.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Python makes decorators fairly easy, and they are really awesome for this kind of features we all need in production environments. &lt;/p&gt;

&lt;p&gt;Caching, unit testing, routing, these are all problems that can be elegantly solved using decorators, and I think, particulary in Python, they are really beginner friendly.&lt;/p&gt;

</description>
      <category>python</category>
      <category>decorators</category>
    </item>
    <item>
      <title>Intersection, union and difference of Sets in Python.</title>
      <dc:creator>Sebastian G. Vinci</dc:creator>
      <pubDate>Mon, 04 Feb 2019 20:47:50 +0000</pubDate>
      <link>https://dev.to/svinci/intersection-union-and-difference-of-sets-in-python-4gkn</link>
      <guid>https://dev.to/svinci/intersection-union-and-difference-of-sets-in-python-4gkn</guid>
      <description>&lt;p&gt;I wanted to talk about &lt;em&gt;sets&lt;/em&gt;, and four great operations they provide:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Intersection&lt;/strong&gt;: Elements two sets have in common.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Union&lt;/strong&gt;: All the elements from both sets.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Difference&lt;/strong&gt;: Elements present on one set, but not on the other.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Symmetric Difference&lt;/strong&gt;: Elements from both sets, that are not present on the other.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We are going to do this using &lt;em&gt;Python (3.7)&lt;/em&gt;, because it rules!&lt;/p&gt;

&lt;p&gt;So, let's dive right into it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Some basic understanding of sets.
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Sets are data structures&lt;/strong&gt; that, based on specific rules they define, provide certain cool operations and guarantees to make a lot of things easier when we use them. &lt;/p&gt;

&lt;p&gt;Two basic rules we need to know are these:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Items in a set are unique.&lt;/strong&gt; We can not have a set that contains two items that are equal. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Items in a set are not ordered.&lt;/strong&gt; Depending on the implementation, items may be sorted using the hash of the value stored, but when you use sets you need to assume items are ordered in a random manner.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And a cool guarantee they provide us: Checking if an element is present on a set has a &lt;strong&gt;time complexity constant (O(1))&lt;/strong&gt;, always. This means, checking if a set contains an element is &lt;em&gt;super fast&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The most popular implementation of a set used to achieve this is the &lt;em&gt;hashed set&lt;/em&gt;. Oversimplified, it basically &lt;em&gt;stores the items in a key-value store, where the key is a hash of the value stored.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So, to create a set in Python we use the constructor &lt;code&gt;set&lt;/code&gt; which receives any iterable: &lt;code&gt;my_pets = set(['dog', 'cat', 'parrot'])&lt;/code&gt; &lt;em&gt;(no, I don't have a parrot, nor a cat, dog person here).&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;Curly braces may be used too, which will avoid creating an intermediate list, but as they are &lt;em&gt;also&lt;/em&gt; used for dictionaries, &lt;strong&gt;you can not create an empty set with curly braces.&lt;/strong&gt; Also, someone can get confused, so I avoid them and stick to the constructor.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sets are collections&lt;/strong&gt;, therefore &lt;strong&gt;they are iterable&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_pets = set(['dog', 'cat', 'parrot'])
for pet in my_pets:
    print('Hello, {}!'.format(pet))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above program serves as a demonstration of how elements in a set are ordered, below is the output of the program where you can see the order I defined was not respected by the interpreter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hello, dog!
Hello, parrot!
Hello, cat!
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So, with this information, let's just dive into these cool operations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Intersection
&lt;/h2&gt;

&lt;p&gt;The intersection between two sets, results in a third set that contains the elements present in both. &lt;/p&gt;

&lt;p&gt;For example, if I calculate the intersection between &lt;code&gt;{1, 2, 3}&lt;/code&gt; and &lt;code&gt;{2, 3, 4}&lt;/code&gt;, the output will be &lt;code&gt;{2, 3}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If this helps you understand, here is a naive implementation in Python:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = set([1, 2, 3])
b = set([2, 3, 4])
result = {element for element in a if element in b}
print(result)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Man, is Python awesome or what? Of course, this will print &lt;code&gt;{2, 3}&lt;/code&gt; as expected. Anyway, that was irrelevant because Python provides a function to do this as part of its standard library. The same can be achieved with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = set([1, 2, 3])
b = set([2, 3, 4])
result = a.intersection(b)
print(result)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Notice that, because of the nature of the operation, &lt;code&gt;a.intersection(b)&lt;/code&gt; and &lt;code&gt;b.intersection(a)&lt;/code&gt; is the same. It is a commutative operation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Union
&lt;/h2&gt;

&lt;p&gt;The union between two sets, results in a third set with all the elements from both sets. &lt;/p&gt;

&lt;p&gt;For example, if I calculate the union between &lt;code&gt;{1, 2, 3}&lt;/code&gt; and &lt;code&gt;{2, 3, 4}&lt;/code&gt;, the output will be &lt;code&gt;{1, 2, 3, 4}&lt;/code&gt;. Kind of like a concatenation, but having in mind that sets can not have repeated elements.&lt;/p&gt;

&lt;p&gt;Again, let's see a naive implementation in Python:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = set([1, 2, 3])
b = set([2, 3, 4])
c = set()

for element in a: 
    c.add(element)

for element in b: 
    c.add(element)

print(c)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As expected, the output is &lt;code&gt;{1, 2, 3, 4}&lt;/code&gt;. Again, though, Python does provide a native function to do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = set([1, 2, 3])
b = set([2, 3, 4])
c = a.union(b)
print(c)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Notice that, because of the nature of the operation, &lt;code&gt;a.union(b)&lt;/code&gt; and &lt;code&gt;b.union(a)&lt;/code&gt; is the same. It is a commutative operation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Difference
&lt;/h2&gt;

&lt;p&gt;The difference between two sets results in a third set with the element from the first, that are not present on the second. Right now I'm going to tell you, this operation is not commutative.&lt;/p&gt;

&lt;p&gt;For example, if I have a set &lt;code&gt;a = {1, 2, 3}&lt;/code&gt; and a set &lt;code&gt;b = {2, 3, 4}&lt;/code&gt;, the difference between &lt;code&gt;a and b&lt;/code&gt; is &lt;code&gt;{1}&lt;/code&gt; and the difference between &lt;code&gt;b and a&lt;/code&gt; is &lt;code&gt;{4}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here's a naive implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = set([1, 2, 3])
b = set([2, 3, 4])
c = {element for element in a if element not in b}
print(c)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This outputs &lt;code&gt;{1}&lt;/code&gt; as expected, and will print &lt;code&gt;{4}&lt;/code&gt; if we invert &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt;. Again, an implementation using Python's standard lib:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = set([1, 2, 3])
b = set([2, 3, 4])
c = a.difference(b)
print(c)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Symmetric difference
&lt;/h2&gt;

&lt;p&gt;The symmetric difference between two sets results in a third set with the elements, from both sets, that are not present on the other. &lt;/p&gt;

&lt;p&gt;For example, if I calculate the symmetric difference between &lt;code&gt;{1, 2, 3}&lt;/code&gt; and &lt;code&gt;{2, 3, 4}&lt;/code&gt;, the output will be &lt;code&gt;{1, 4}&lt;/code&gt;. This operation is commutative.&lt;/p&gt;

&lt;p&gt;Here's a naive implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = set([1, 2, 3])
b = set([2, 3, 4])
c = set()

for element in a:
    if element not in b:
        c.add(element)

for element in b:
    if element not in a:
        c.add(element)

print(c)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above implementation will print &lt;code&gt;{1, 4}&lt;/code&gt;, as expected. Of course, Python has this on its standard libary too: &lt;code&gt;symmetric_difference&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = set([1, 2, 3])
b = set([2, 3, 4])
c = a.symmetric_difference(b)
print(c)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Sets are really useful, and actually pretty fun. Give them a try. I lived a lot of time constrained to lists, and when I finally sat down and learned how to work with sets started finding better, more elegant solutions to a lot of problems.&lt;/p&gt;

</description>
      <category>python</category>
      <category>sets</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Scala REST API documented with Swagger (Part 2 of 2)</title>
      <dc:creator>Sebastian G. Vinci</dc:creator>
      <pubDate>Wed, 19 Apr 2017 19:09:48 +0000</pubDate>
      <link>https://dev.to/svinci/scala-rest-api-documented-with-swagger-part-2-of-2</link>
      <guid>https://dev.to/svinci/scala-rest-api-documented-with-swagger-part-2-of-2</guid>
      <description>&lt;p&gt;This is the continuation of a post you can find &lt;a href="https://dev.to/svinci/scala-rest-api-documented-with-swagger-part-1-of-2"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where we left off...
&lt;/h2&gt;

&lt;p&gt;So, we have an API that has a status endpoint and the code in place to document it with swagger.&lt;/p&gt;

&lt;p&gt;Starting the service, we'll see that our documentation is available at &lt;code&gt;http://localhost:8080/docs&lt;/code&gt;, and we have a status endpoint at &lt;code&gt;http://localhost:8080/professionals-api/status&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So, let's keep going!&lt;/p&gt;

&lt;h2&gt;
  
  
  Professionals API
&lt;/h2&gt;

&lt;p&gt;Let's create our model at a package called &lt;code&gt;com.svinci.professionals.api.domain.professional&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First, professionals have jobs where they excel, right? And they may have more than one, so we'll need a case class for a job:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;case class Job(name: String, description: String)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Now, contact information will be displayed or not according whether the client is authenticated or not, so we'll need a case class for the contact information:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;case class ContactInformation(phone: String, eMail: String, address: String)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;And then, we just need a professional. It will have an id, a name, an age, a list of jobs and, optionally, contact information:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;case class Professional(id: String, name: String, age: Int, jobs: List[Job], contactInformation: Option[ContactInformation])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Also, when a client creates a professional, the id should be generated by the API, and contact information should be mandatory, so we'll need a create request, and it would be nice if it knew how to transform itself to a full professional:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;case class ProfessionalCreationRequest(name: String, age: Int, jobs: List[Job], contactInformation: ContactInformation) {

  def toProfessional: Professional = Professional(
    id = UUID.randomUUID().toString,
    name = name,
    age = age,
    jobs = jobs,
    contactInformation = Option(contactInformation)
  )

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That should do it, let's move on to the repository. Create a file called &lt;code&gt;ProfessionalRepository.scala&lt;/code&gt; with the following content, the code is explained with comments:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.domain.professional

import scala.collection.concurrent.TrieMap

/**
  * We are using cake pattern to solve dependency injection without using any library. You can find a really good explanation of this pattern at http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth.
  *
  * This component holds the interface for professionals repository.
  */
trait ProfessionalRepositoryComponent {

  /**
    * Professional repository instance definition.
    */
  def professionalRepositoryInstance: ProfessionalRepository

  /**
    * Professional repository interface.
    */
  trait ProfessionalRepository {

    /**
      * Receives a creation request, transforms it to a Professional and stores it. Returns the created professional.
      */
    def create(professionalCreationRequest: ProfessionalCreationRequest): Professional

    /**
      * Removes the professional that has the given id. Returns the removed professional if any.
      */
    def remove(professionalId: String): Option[Professional]

    /**
      * Returns the professional that has the given id if any.
      */
    def findById(professionalId: String, displayContactInformation: Boolean): Option[Professional]

    /**
      * Returns a list with all the stored professionals.
      */
    def all(displayContactInformation: Boolean): List[Professional]

  }

}

/**
  * This component defines an implementation of ProfessionalRepository which holds the data in memory.
  */
trait InMemoryProfessionalRepositoryComponent extends ProfessionalRepositoryComponent {

  /**
    * In memory professional repository instantiation.
    */
  override def professionalRepositoryInstance: ProfessionalRepository = new InMemoryProfessionalRepository

  /**
    * In memory implementation of a professional repository.
    */
  class InMemoryProfessionalRepository extends ProfessionalRepository {

    /**
      * This is the data structure chosen to store the professionals.
      * In this Map you'll find professionals indexed by their ids.
      * TrieMap was chosen to make this class thread safe.
      */
    private[this] val storage: TrieMap[String, Professional] = TrieMap()

    /**
      * @inheritdoc
      */
    override def create(professionalCreationRequest: ProfessionalCreationRequest): Professional = {
      val professional = professionalCreationRequest.toProfessional
      storage.put(professional.id, professional)
      professional
    }

    /**
      * @inheritdoc
      */
    override def remove(professionalId: String): Option[Professional] = storage.remove(professionalId)

    /**
      * @inheritdoc
      */
    override def findById(professionalId: String, displayContactInformation: Boolean): Option[Professional] = {
      val maybeProfessional = storage.get(professionalId)

      if (displayContactInformation) {
        return maybeProfessional
      }

      maybeProfessional.map(professional =&amp;gt; professional.copy(contactInformation = None))
    }

    /**
      * @inheritdoc
      */
    override def all(displayContactInformation: Boolean): List[Professional] = {
      val allProfessionals = storage.values.toList

      if (displayContactInformation) {
        return allProfessionals
      }

      allProfessionals.map(professional =&amp;gt; professional.copy(contactInformation = None))
    }

  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that the read operations receive a flag called &lt;code&gt;displayContactInformation&lt;/code&gt;, if it's true, they just return what they have, but if it's false they copy the professionals omitting the contact information.&lt;/p&gt;

&lt;p&gt;I wouldn't normally put that logic in the repository, I would have a service layer or something, but as this is a really small API, I prefer keeping it simple.&lt;/p&gt;

&lt;p&gt;Now we just need our servlet, we'll need a file called &lt;code&gt;ProfessionalServlet.scala&lt;/code&gt; with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.domain.professional

import com.svinci.professionals.api.infrastructure.ServletSupport

/**
  * We are using cake pattern to solve dependency injection without using any library. You can find a really good explanation of this pattern at http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth.
  *
  * As this is an entry point to our application, there is no need to create an interface (it's a servlet after all, so there are no functions exposed).
  */
trait ProfessionalServletComponent {

  /**
    * As defined by cake pattern, with self type annotations we are defining that any class that extends this trait, needs to extend ProfessionalRepositoryComponent too.
    * This makes the interface and instance defined by ProfessionalRepositoryComponent available in this trait.
    */
  this: ProfessionalRepositoryComponent =&amp;gt;

  /**
    * Professional servlet instantiation.
    */
  def professionalServletInstance: ProfessionalServlet = new ProfessionalServlet(professionalRepositoryInstance)

  /**
    * This is the scalatra servlet that will serve our professionals management endpoints.
    */
  class ProfessionalServlet(val repository: ProfessionalRepository) extends ServletSupport {

    /**
      * This value defines the documentation for this endpoint. We are giving the endpoint a name, the return type, a description/summary and the schema for the expected boy.
      */
    private[this] val createProfessional = apiOperation[Professional]("create") summary "Insert a professional in the system" parameter bodyParam[ProfessionalCreationRequest]
    /**
      * We are routing our creation endpoint to the root of this servlet, passing the api operation for swagger to document.
      */
    post("/", operation(createProfessional)) {
      val creationRequest = parsedBody.extract[ProfessionalCreationRequest]
      repository.create(creationRequest)
    }

    /**
      * This value defines the documentation for this endpoint. We are giving the endpoint a name, the return type, a description/summary and the specifications for the id path param.
      */
    private[this] val removeProfessional = apiOperation[Option[Professional]]("remove") summary "Remove a professional by its id." parameter pathParam[String]("Id of the professional to remove")
    /**
      * We are routing our removal endpoint to the root of this servlet with the id as a path param, passing the api operation for swagger to document.
      */
    delete("/:id", operation(removeProfessional)) {
      val professionalId = params('id)
      repository.remove(professionalId)
    }

    /**
      * This value defines the documentation for this endpoint. We are giving the endpoint a name, the return type, a description/summary and the specifications for the id path parameter.
      */
    private[this] val findById = apiOperation[Option[Professional]]("findById") summary "Find a professional by its id." parameter pathParam[String]("id of the professional you are looking for.")
    /**
      * We are routing our findById endpoint to the root of this servlet with the id as a path param, passing the api operation for swagger to document.
      */
    get("/:id", operation(findById)) {
      val professionalId = params('id)
      val authenticated = request.getAttribute("authenticated").asInstanceOf[Boolean]
      repository.findById(professionalId, authenticated)
    }

    /**
      * This value defines the documentation for this endpoint. We are giving the endpoint a name, the return type and a description/summary.
      */
    private[this] val all = apiOperation[List[Professional]]("allProfessionals") summary "Retrieve all professionals."
    /**
      * We are routing our all endpoint to the root of this servlet, passing the api operation for swagger to document.
      */
    get("/", operation(all)) {
      val authenticated = request.getAttribute("authenticated").asInstanceOf[Boolean]
      repository.all(authenticated)
    }

    /**
      * This is the description of this servlet, requested by swagger.
      */
    override protected def applicationDescription: String = "Professionals management API."

  }

}

/**
  * This is the default instance of ProfessionalServletComponent. Here we define that the ProfessionalServletComponent will use the InMemoryProfessionalRepositoryComponent.
  */
object DefaultProfessionalServletComponent extends ProfessionalServletComponent with InMemoryProfessionalRepositoryComponent

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One thing to notice about this servlet is that we are retrieving an attribute from the request to check if the client is authenticated: &lt;code&gt;request.getAttribute("authenticated").asInstanceOf[Boolean]&lt;/code&gt;. This attribute should be populated by a filter or a before handler. Let's add it to the &lt;code&gt;ServletSupport&lt;/code&gt; trait, in the &lt;code&gt;before&lt;/code&gt; execution.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   /**
    * From the servlet request, check if the client is authenticated.
    *
    * This function can be exposed as protected as is, and let the servlets that extend ServletSupport use it,
    * but that wouldn't be convenient in a real situation, as checking if an authentication token is actually valid
    * would have performance implications (query to a database, REST API call, etc.).
    */
  private[this] def isAuthenticated()(implicit request: HttpServletRequest): Boolean = {
    val authenticationToken: Option[String] = Option(request.getHeader("X-PROFESSIONALS-API-TOKEN"))

    // Here you may perform token validation calling an authentication service or something.
    // We'll keep it simple in this example, and we'll assume the client is authenticated if the header is present.
    authenticationToken.isDefined
  }

  /**
   * Before every request made to a servlet that extends this trait, the function passed to `before()` will be executed.
   * We are using this to :
   *   - Set the Content-Type header for every request, as we are always going to return JSON.
   *   - Set the date to the request, so we can calculate spent time afterwards.
   *   - Generate a transaction identifier, an add it to the MDC, so we know which lines of logs were triggered by which request.
   *   - Check if the client is authenticated and add the flag to the request attributes.
   *   - Log that a request arrived.
   */
  before() {

    contentType = "application/json"
    request.setAttribute("startTime", new Date().getTime)
    MDC.put("tid", UUID.randomUUID().toString.substring(0, 8))

    val authenticated = isAuthenticated()
    request.setAttribute("authenticated", authenticated)

    logger.info(s"Received request ${request.getMethod} at ${request.getRequestURI}")

  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There, we are creating the function &lt;code&gt;isAuthenticated&lt;/code&gt; and calling it from the function we pass to &lt;code&gt;before()&lt;/code&gt; that was already written from the previous post.&lt;/p&gt;

&lt;p&gt;Now, we need to add the professional servlet to our &lt;code&gt;Module&lt;/code&gt; object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  /**
    * Default instance of ProfessionalServlet
    */
  def professionalServlet: DefaultProfessionalServletComponent.ProfessionalServlet = DefaultProfessionalServletComponent.professionalServletInstance

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now we can mount it in our &lt;code&gt;ScalatraBootstrap&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    context.mount(Module.professionalServlet, "/professionals-api/professionals", "professionals")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's time to test it, let's boot the sbt console running &lt;code&gt;sbt&lt;/code&gt; at the root of the project and then running &lt;code&gt;jetty:start&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's create a professional:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ curl -v localhost:8080/professionals-api/professionals -X POST -H "Content-Type: application/json" -d '{"name": "Mario", "age": 45, "jobs": [{"name": "Plumber", "description": "Fixing your pipes broh!"}], "contactInformation": {"phone": "555-1234", "eMail": "mario@gmail.com", "address": "Check your pipes ;)"}}'

{"id":"f967b053-68c1-41af-a8b9-27135516c0fc","name":"Mario","age":45,"jobs":[{"name":"Plumber","description":"Fixing your pipes broh!"}],"contactInformation":{"phone":"555-1234","eMail":"mario@gmail.com","address":"Check your pipes ;)"}}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you see there, the API received the request, and returned the created Mario. Let's retrieve all professionals now, to check the API is actually storing stuff.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ curl localhost:8080/professionals-api/professionals

[{"id":"f967b053-68c1-41af-a8b9-27135516c0fc","name":"Mario","age":45,"jobs":[{"name":"Plumber","description":"Fixing your pipes broh!"}]}]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There it is! You can see Mario there, yet it hasn't contact information, shall we check that the authentication works?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ curl localhost:8080/professionals-api/professionals -H "X-PROFESSIONALS-API-TOKEN: 1234"

[{"id":"f967b053-68c1-41af-a8b9-27135516c0fc","name":"Mario","age":45,"jobs":[{"name":"Plumber","description":"Fixing your pipes broh!"}],"contactInformation":{"phone":"555-1234","eMail":"mario@gmail.com","address":"Check your pipes ;)"}}]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Awesome! We can see his mail and phone now. Let's retrieve Mario by his id &lt;code&gt;f967b053-68c1-41af-a8b9-27135516c0fc&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ curl localhost:8080/professionals-api/professionals/f967b053-68c1-41af-a8b9-27135516c0fc -H "X-PROFESSIONALS-API-TOKEN: 1234"

{"id":"f967b053-68c1-41af-a8b9-27135516c0fc","name":"Mario","age":45,"jobs":[{"name":"Plumber","description":"Fixing your pipes broh!"}],"contactInformation":{"phone":"555-1234","eMail":"mario@gmail.com","address":"Check your pipes ;)"}}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is great, let's remove Mario now, and move on to check the documentation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ curl localhost:8080/professionals-api/professionals/f967b053-68c1-41af-a8b9-27135516c0fc -H "X-PROFESSIONALS-API-TOKEN: 1234" -X DELETE

{"id":"f967b053-68c1-41af-a8b9-27135516c0fc","name":"Mario","age":45,"jobs":[{"name":"Plumber","description":"Fixing your pipes broh!"}],"contactInformation":{"phone":"555-1234","eMail":"mario@gmail.com","address":"Check your pipes ;)"}}

$ curl localhost:8080/professionals-api/professionals -H "X-PROFESSIONALS-API-TOKEN: 1234"
[]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great, we removed it and then the API is no longer retrieving it. Now, it's time to see how the documentation is working, but I don't want to keep reading JSON, I mean, JSON is a good format, and it's easy to read... but wouldn't a UI be great for this? It shouldn't be that hard to make...&lt;/p&gt;

&lt;h2&gt;
  
  
  Swagger UI
&lt;/h2&gt;

&lt;p&gt;Well it isn't, and they actually did it. You'll need docker to keep following this example btw. Installation instructions can be found &lt;a href="https://www.docker.com/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Execute the following command one you have docker installed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker run -p 8081:8080 --name swagger-ui-instance -d swaggerapi/swagger-ui:v2.2.9
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will boot a docker container that serves swagger ui with an NGINX. It doesn't matter anyway. You just visit &lt;code&gt;http://localhost:8081&lt;/code&gt; in your browser, find the text input in the top navigation bad, type &lt;code&gt;http://localhost:8080/docs&lt;/code&gt; there and hit &lt;code&gt;Explore&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;There you have it! An interactive graphic interface to see your API documentation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;See the version tag &lt;code&gt;v2.2.9&lt;/code&gt; we are setting when we run the docker instance? That's important. As I said on the previous post, scalatra swagger provides Swagger V1 JSONS, which are deprecated, and &lt;code&gt;v2.2.9&lt;/code&gt; of swagger UI is the latest version that support Swagger V1.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Packaging a standalone JAR
&lt;/h2&gt;

&lt;p&gt;This is a quick step, we just need to add two lines to the &lt;code&gt;build.sbt&lt;/code&gt; file, as most of the setup was already done when we started the project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mainClass in Compile := Some("com.svinci.professionals.api.JettyLauncher")
mainClass in assembly := Some("com.svinci.professionals.api.JettyLauncher")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way, we are telling assembly which is our main class. That &lt;code&gt;JettyLauncher&lt;/code&gt; object was written in the previous post and it's an object that's capable of starting the JettyServer as the scalatra plugin does.&lt;/p&gt;

&lt;p&gt;Now we'll run some commands:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First, to assembly the JAR we run &lt;code&gt;sbt assembly&lt;/code&gt;. There are going to be a couple WARN lines of log, but they aren't important.&lt;/li&gt;
&lt;li&gt;Second, we go to the directory where the JAR is located doing &lt;code&gt;cd target/scala-2.11&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;There you'll find the JAR called &lt;code&gt;professionals-api.jar&lt;/code&gt;. By doing &lt;code&gt;java -jar professionals-api.jar&lt;/code&gt; you can run the JAR with the default configuration. &lt;/li&gt;
&lt;li&gt;The configuration present in &lt;code&gt;application.conf&lt;/code&gt; can be overridden wit java options as in &lt;code&gt;java -Dapplication.port=8082 -jar professionals-api.jar&lt;/code&gt; &amp;lt;- this command will run the server but it will listen in the port 8082.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Scala, SBT, Scalatra and Swagger are awesome. Yes, I'd like to move to Swagger V2, but it isn't that problematic. APIs written with these technologies work just fine and perform very well.&lt;/p&gt;

&lt;p&gt;You can find the code to this post series &lt;a href="https://github.com/svinci/scala-scalatra-swagger-example"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thanks a lot for reading!&lt;/p&gt;

&lt;p&gt;See you in the comments!&lt;/p&gt;

</description>
      <category>scala</category>
      <category>rest</category>
      <category>swagger</category>
      <category>scalatra</category>
    </item>
    <item>
      <title>Scala REST API documented with Swagger (Part 1 of 2)</title>
      <dc:creator>Sebastian G. Vinci</dc:creator>
      <pubDate>Mon, 17 Apr 2017 01:40:41 +0000</pubDate>
      <link>https://dev.to/svinci/scala-rest-api-documented-with-swagger-part-1-of-2</link>
      <guid>https://dev.to/svinci/scala-rest-api-documented-with-swagger-part-1-of-2</guid>
      <description>&lt;p&gt;In this post series we are going to build a REST API using SBT, Scala and Scalatra. Something I like a lot about Scalatra is that it has a library to document your API using Swagger with very little efort.&lt;/p&gt;

&lt;p&gt;Our API will be very simple. It will manage a catalog of professionals, but contact information will only be provided if the client is authenticated.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;DOWNSIDE: Scalatra swagger only supports swagger v1, which is deprecated now. There are tools to convert swagger v1 JSONs to swagger v2, and even to RAML, so this doesn't really bother me.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What we'll build on this part
&lt;/h2&gt;

&lt;p&gt;Part 1 will only consist of the set up of the project, a status endpoint and the implementation of a servlet to retrieve swagger documentation. &lt;/p&gt;

&lt;p&gt;The endpoints to manage professionals, the authentication filter, the standalone build (jar deployment) and a UI to see the API documentation on an interactive manner will be approached on the second part.&lt;/p&gt;

&lt;h2&gt;
  
  
  Preconditions
&lt;/h2&gt;

&lt;p&gt;I'll assume you are familiar with the Scala language, SBT and REST.&lt;/p&gt;

&lt;p&gt;To work through this tutorial you'll need to install JDK 8 (open jdk is fine) and &lt;a href="http://www.scala-sbt.org/download.html"&gt;SBT&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;All the commands I'll provide to install, run and do stuff were tested on Linux Mint 18. They'll probably work on Mac OS without any issue. If you're working on windows I'm really sorry.&lt;/p&gt;

&lt;h2&gt;
  
  
  Set Up
&lt;/h2&gt;

&lt;p&gt;I'll show how to create this project by hand, but there are project templates and stuff you can use. I think SBT has a command to generate empty projects, but also lighbend activator is a fine tool to start from a template.&lt;/p&gt;

&lt;p&gt;First of all, let's create our project directory running &lt;code&gt;mkdir scala-scalatra-swagger-example&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, this are the directories you'll need to have:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;project&lt;/li&gt;
&lt;li&gt;src/main/resources&lt;/li&gt;
&lt;li&gt;src/main/scala&lt;/li&gt;
&lt;li&gt;src/main/webapp/WEB-INF&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Under &lt;code&gt;project&lt;/code&gt; directory, you need to create a file called &lt;code&gt;build.properties&lt;/code&gt; with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sbt.version=0.13.13

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are defining our project to be built using sbt 0.13.13.&lt;/p&gt;

&lt;p&gt;Also, under &lt;code&gt;project&lt;/code&gt; directory, you'll need a file called &lt;code&gt;plugins.sbt&lt;/code&gt; with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;addSbtPlugin("org.scalatra.sbt" % "scalatra-sbt" % "0.5.1")

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.4")

addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are importing scalatra SBT plugin, needed to work with scalatra (it will provide some tools to work with Jetty and stuff). Then, we import assembly, which we'll use to build our standalone jar. Finally, we are adding scalariform, so our code gets formated on compile time.&lt;/p&gt;

&lt;p&gt;Now, under &lt;code&gt;src/main/webapp/WEB-INF&lt;/code&gt; we'll need a file called &lt;code&gt;web.xml&lt;/code&gt; with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"&amp;gt;

  &amp;lt;!--
    This listener loads a class in the default package called ScalatraBootstrap.
    That class should implement org.scalatra.LifeCycle.  Your app can be
    configured in Scala code there.
  --&amp;gt;
  &amp;lt;listener&amp;gt;
    &amp;lt;listener-class&amp;gt;org.scalatra.servlet.ScalatraListener&amp;lt;/listener-class&amp;gt;
  &amp;lt;/listener&amp;gt;
&amp;lt;/web-app&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This basically tells jetty that our only listener is the one provided by Scalatra.&lt;/p&gt;

&lt;p&gt;Now, under &lt;code&gt;src/main/resources&lt;/code&gt; we'll need our application configuration file, called &lt;code&gt;application.conf&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;application.port=8080

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Yes, it only contains the port where the API will listen, but I wanted to show how configuration will work on an application like this, as it is a real need in production.&lt;/p&gt;

&lt;p&gt;Also, logging is a necessity in production, so, under &lt;code&gt;src/main/resources&lt;/code&gt; too, we'll need our &lt;code&gt;logback.xml&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;configuration&amp;gt;

  &amp;lt;appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"&amp;gt;
    &amp;lt;encoder&amp;gt;
      &amp;lt;pattern&amp;gt;[%d] [%level] [tid: %X{tid:-none}] [%t] [%logger{39}] : %m%n%rEx{10}&amp;lt;/pattern&amp;gt;
      &amp;lt;charset&amp;gt;utf8&amp;lt;/charset&amp;gt;
    &amp;lt;/encoder&amp;gt;
  &amp;lt;/appender&amp;gt;

  &amp;lt;root level="INFO"&amp;gt;
    &amp;lt;appender-ref ref="CONSOLE"/&amp;gt;
  &amp;lt;/root&amp;gt;

&amp;lt;/configuration&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This only defines a console appender (sends logs to the standard output), with a really standard pattern (the only weird thing is the &lt;code&gt;tid&lt;/code&gt; thingy, we'll talk about it later).&lt;/p&gt;

&lt;p&gt;Now we'll glue everything together with a &lt;code&gt;build.sbt&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.typesafe.sbt.SbtScalariform
import com.typesafe.sbt.SbtScalariform.ScalariformKeys
import org.scalatra.sbt._

import scalariform.formatter.preferences._

val ScalatraVersion = "2.5.0"

ScalatraPlugin.scalatraSettings

organization := "com.svinci.professionals"

name := "api"

version := "0.0.1-SNAPSHOT"

scalaVersion := "2.11.8"

resolvers += Classpaths.typesafeReleases

SbtScalariform.scalariformSettings

ScalariformKeys.preferences := ScalariformKeys.preferences.value
  .setPreference(AlignSingleLineCaseStatements, true)
  .setPreference(DoubleIndentClassDeclaration, true)
  .setPreference(AlignParameters, true)
  .setPreference(AlignArguments, true)

libraryDependencies ++= Seq(
  "org.scalatra"        %%  "scalatra"          % ScalatraVersion,
  "org.scalatra"        %%  "scalatra-json"     % ScalatraVersion,
  "org.scalatra"        %%  "scalatra-swagger"  % ScalatraVersion,
  "org.json4s"          %%  "json4s-native"     % "3.5.0",
  "org.json4s"          %%  "json4s-jackson"    % "3.5.0",
  "com.typesafe"        %   "config"            % "1.3.1",
  "ch.qos.logback"      %   "logback-classic"   % "1.1.5"             % "runtime",
  "org.eclipse.jetty"   %   "jetty-webapp"      % "9.2.15.v20160210"  % "container;compile",
  "javax.servlet"       %   "javax.servlet-api" % "3.1.0"             % "provided"
)

assemblyJarName in assembly := "professionals-api.jar"

enablePlugins(JettyPlugin)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What's this &lt;code&gt;build.sbt&lt;/code&gt; doing?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;At the top of the file we are importing our plugins and the things we need to set up the build of our project. &lt;/li&gt;
&lt;li&gt;Then we define a value containing scalatra version (2.5.0) and applying &lt;code&gt;ScalatraPlugin.scalatraSettings&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;After that, we are defining some artifact information (organization, name, version, scala version), adding typesafe repository (lightbend used to be called typesafe) to our resolvers and then we configure scalariform.&lt;/li&gt;
&lt;li&gt;Then, our dependencies are being defined. Notice scalatra dependencies, json4s, config, logback and jetty.&lt;/li&gt;
&lt;li&gt;Then, we are configuring assembly, so everything is packaged under a jar called &lt;code&gt;professionals-api.jar&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Finally, we are enabling jetty plugin (it comes with the scalatra plugin).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;At this point, we can run &lt;code&gt;sbt&lt;/code&gt; on the root of the project to see that it's loaded correctly, and even compile it (although there is no code to compile).&lt;/p&gt;

&lt;p&gt;Now it would be the time to open this project with an IDE (yes, I've been using vim up to this point).&lt;/p&gt;

&lt;h2&gt;
  
  
  Utility objects and traits
&lt;/h2&gt;

&lt;p&gt;We will create now some infrastructure for our code. First, let's create our package &lt;code&gt;com.svinci.professionals.api.infrastructure&lt;/code&gt;. Under this package, let's write the following (the code is explained with comments):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A file called &lt;code&gt;Configuration.scala&lt;/code&gt; with the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.infrastructure

import com.typesafe.config.ConfigFactory

/**
  * This will provide a singleton instance of our configuration.
  * Also, it will encapsulate typesafe.config, so the rest of the application doesn't need to know about the configuration library we are using.
  */
object Configuration {

  /**
    * This is our configuration instance. Private and immutable.
    */
  private[this] val configuration = ConfigFactory.load()

  /**
    * Methods like this one should be defined to access any type of configuration from its key.
    * The reason we do it is to define an interface that makes sense for our application, and make the rest of the code
    * agnostic to what library we are using. Just a good practice.
    * @param key Configuration key.
    * @return The configured Int.
    */
  def getInt(key: String): Int = configuration.getInt(key)

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;A file called &lt;code&gt;ApiInformation.scala&lt;/code&gt; with the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.infrastructure

import org.scalatra.swagger.{ApiInfo, Swagger}

/**
  * Information of our API as a whole.
  */
object ProfessionalsApiInfo extends ApiInfo(
  title = "professionals-api",
  description = "Professionals CRUD operations.",
  termsOfServiceUrl = "some terms of service URL",
  contact = "some contact information",
  license = "MIT",
  licenseUrl = "http://opensource.org/licenses/MIT"
)

/**
  * Swagger instance for our API. It's defined  as an object so we have only one instance for all our resources.
  */
object ProfessionalsApiSwagger extends Swagger(swaggerVersion = Swagger.SpecVersion, apiVersion = "1.0.0", apiInfo = ProfessionalsApiInfo)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;A file called &lt;code&gt;ServletSupport.scala&lt;/code&gt; with the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.infrastructure

import java.util.{Date, UUID}

import org.json4s.{DefaultFormats, Formats}
import org.scalatra._
import org.scalatra.json._
import org.scalatra.swagger.SwaggerSupport
import org.slf4j.{LoggerFactory, MDC}

/**
  * We'll have a couple servlets probably (a status endpoint, the CRUD servlet for our professionals, and if we deploy this to production we'll probably add some more),
  * so it's convenient to have the things every servlet will need to define in one trait to extend it.
  * 
  * This trait extends ScalatraServlet and adds json and swagger support.
  */
trait ServletSupport extends ScalatraServlet with JacksonJsonSupport with SwaggerSupport {

  /**
    * As we are going to document every endpoint of our API, we'll need our swagger instance in everyone of our servlets.
    */
  override protected implicit def swagger = ProfessionalsApiSwagger

  /**
    * This is a logger... to log stuff.
    */
  private[this] val logger = LoggerFactory.getLogger(getClass)
  /**
    * Scalatra requires us to define an implicit Formats instance for it to know how we want JSONs to be serialized/deserialized.
    * It provides a DefaultFormats that fill all our needs today, so we'll use it. 
    */
  protected implicit lazy val jsonFormats: Formats = DefaultFormats

  /**
    * Before every request made to a servlet that extends this trait, the function passed to `before()` will be executed.
    * We are using this to :
    *   - Set the Content-Type header for every request, as we are always going to return JSON.
    *   - Set the date to the request, so we can calculate spent time afterwards.
    *   - Generate a transaction identifier, an add it to the MDC, so we know which lines of logs were triggered by which request.
    *   - Log that a request arrived.
    */
  before() {

    contentType = "application/json"
    request.setAttribute("startTime", new Date().getTime)
    MDC.put("tid", UUID.randomUUID().toString.substring(0, 8))

    logger.info(s"Received request ${request.getMethod} at ${request.getRequestURI}")

  }

  /**
    * NotFound handler. We just want to set the status code, and avoid the huge stack traces scalatra returns in the body.
    */
  notFound {

    response.setStatus(404)

  }

  /**
    * After every request made to a servlet that extends this trait, the function passed to `after()` will be executed.
    * We are using this to:
    *   - Retrieve the start time added in the `before()` handler an calculate how much time the API took to respond.
    *   - Log that the request handling finished, with how much time it took.
    */
  after() {

    val startTime: Long = request.getAttribute("startTime").asInstanceOf[Long]
    val spentTime: Long = new Date().getTime - startTime
    logger.info(s"Request ${request.getMethod} at ${request.getRequestURI} took ${spentTime}ms")

  }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Status Endpoint
&lt;/h2&gt;

&lt;p&gt;We'll code now a status endpoint that will always return a JSON with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "healthy": true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you had a database, or an API you depend on, you could add their statuses there. First of all, let's create our package &lt;code&gt;com.svinci.professionals.api.domain.status&lt;/code&gt; and, under this package, write the following (the code is explained with comments):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A file called &lt;code&gt;Status.scala&lt;/code&gt; with the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.domain.status

/**
  * This is the object our status endpoint will convert to JSON and return.
  */
case class Status(healthy: Boolean)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;A file called &lt;code&gt;StatusService.scala&lt;/code&gt; with the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.domain.status

/**
  * We are using cake pattern to solve dependency injection without using any library. You can find a really good explanation of this pattern at http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth.
  * 
  * This is the component that defines a StatusService interface (trait, actually), and names an instance of it.
  */
trait StatusServiceComponent {

  /**
    * This is the definition of the instance of StatusService an implementation of this component will hold.
    */
  def statusServiceInstance: StatusService

  /**
    * StatusService interface definition.
    */
  trait StatusService {

    /**
      * Retrieve the application status.
      * @return The application status.
      */
    def status: Status

  }

}

/**
  * Default StatusServiceComponent implementation.
  */
trait DefaultStatusServiceComponent extends StatusServiceComponent {

  /**
    * Here, we define how the DefaultStatusService is created.
    */
  override def statusServiceInstance: StatusService = new DefaultStatusService

  /**
    * Default StatusService implementation.
    */
  class DefaultStatusService extends StatusService {

    /**
      * @inheritdoc
      */
    override def status: Status = Status(healthy = true)

  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;A file called &lt;code&gt;StatusServlet.scala&lt;/code&gt; with the following content:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.domain.status

import com.svinci.professionals.api.infrastructure.ServletSupport

/**
  * We are using cake pattern to solve dependency injection without using any library. You can find a really good explanation of this pattern at http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth.
  *
  * As this is an entry point to our application, there is no need to create an interface (it's a servlet after all, so there are no functions exposed).
  */
trait StatusServletComponent {

  /**
    * As defined by cake pattern, with self type annotations we are defining that any class that extends this trait, needs to extend StatusServiceComponent too.
    * This makes the interface and instance defined by StatusServiceComponent available in this trait.
    */
  this: StatusServiceComponent =&amp;gt;

  /**
    * This is the StatusServlet instance held by this component. Notice that we are instantiating StatusServlet passing the statusServiceInstance provided by StatusServiceComponent.
    */
  def statusServletInstance: StatusServlet = new StatusServlet(statusService = statusServiceInstance)

  /**
    * This is the scalatra servlet that will serve our status endpoint.
    */
  class StatusServlet(val statusService: StatusService) extends ServletSupport {

    /**
      * This value defines the documentation for this endpoint. We are giving the endpoint a name, the return type and a description/summary.
      */
    private[this] val getStatus = apiOperation[Status]("status") summary "Retrieve API status."

    /**
      * We are routing our status endpoint to the root of this servlet, and passing to scalatra our apiOperation.
      */
    get("/", operation(getStatus)) {
      statusService.status
    }

    /**
      * This is the description of this servlet, requested by swagger.
      */
    override protected def applicationDescription: String = "API Status."

  }

}

/**
  * This is the default instance of StatusServletComponent. Here we define that the StatusServletComponent will use the DefaultStatusServiceComponent.
  */
object DefaultStatusServletComponent extends StatusServletComponent with DefaultStatusServiceComponent

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we go back to the package called &lt;code&gt;com.svinci.professionals.api.infrastructure&lt;/code&gt; and create a file called &lt;code&gt;Module.scala&lt;/code&gt; with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.infrastructure

import com.svinci.professionals.api.domain.status.DefaultStatusServletComponent

/**
  * We are using cake pattern to solve dependency injection without using any library. You can find a really good explanation of this pattern at http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth.
  *
  * In this object we'll hold all the instances required by our application.
  */
object Module {

  /**
    * Default instance of StatusServlet.
    */
  def statusServlet: DefaultStatusServletComponent.StatusServlet = DefaultStatusServletComponent.statusServletInstance

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, for our API to run we'll need an application to run, just as any scala application. Under a package called &lt;code&gt;com.svinci.professionals.api&lt;/code&gt; we'll write a file called &lt;code&gt;JettyLauncher.scala&lt;/code&gt; with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api

import com.svinci.professionals.api.infrastructure.Configuration
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.DefaultServlet
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

/**
  * This is the MainClass of our application.
  */
object JettyLauncher extends App {

  /**
    * Server instantiation. We are retrieving the port we need to listen at from our Configuration object.
    */
  val server = new Server(Configuration.getInt("application.port"))

  /**
    * Web application context instantiation.
    * This class will hold the context path, the resource base, the event listener and one servlet.
    */
  val context = new WebAppContext()

  context setContextPath "/"
  context.setResourceBase("src/main/webapp")
  context.addEventListener(new ScalatraListener)  // We use scalatra listener as event listener.
  context.addServlet(classOf[DefaultServlet], "/")  // We don't need to add our servlets here, we're going to add them using the scalatra life cycle.

  server.setHandler(context)  // We add the WebAppContext to the server.

  server.start()  // Start the server.
  server.join()  // Join the server's thread pool so the application doesn't quit.

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now we need to add our servlets to the scalatra lyfe cycle, so we write a file called &lt;code&gt;ScalatraBootstrap.scala&lt;/code&gt; under the &lt;code&gt;src/main/scala&lt;/code&gt; directory (outside any package) with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api

import javax.servlet.ServletContext

import com.svinci.professionals.api.infrastructure.Module
import org.scalatra._
import org.slf4j.LoggerFactory

/**
  * This class in looked up by scalatra and automatically instantiated. Here we need to code all the start up code of our API.
  */
class ScalatraBootstrap extends LifeCycle {

  private[this] val logger = LoggerFactory.getLogger(getClass)

  /**
    * In the method we need to mount our servlets to the ServletContext provided as parameter.
    * Any additional startup code should be wrote here too (warm up, scheduled tasks initialization, etc.).
    */
  override def init(context: ServletContext) {

    logger.info(context.getContextPath)

    logger.info("Mounting Changas API servlets.")
    context.mount(Module.statusServlet, "/professionals-api/status", "status")
    logger.info(s"API started.")

  }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see there, we are mounting our status servlet to the path &lt;code&gt;/professionals-api/status&lt;/code&gt;, so all the routing we do inside the servlet will be relative to that path. The third parameter we pass to the &lt;code&gt;mount&lt;/code&gt; method is a name we are assigning to that servlet.&lt;/p&gt;

&lt;p&gt;This class needs to be in that location so scalatra can find it. If you place it anywhere else you'll see an assertion error: &lt;code&gt;java.lang.AssertionError: assertion failed: No lifecycle class found!&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now it's time to test our server and our status endpoint. Boot the sbt console by running &lt;code&gt;sbt&lt;/code&gt; on the root of the project, and once inside run &lt;code&gt;jetty:start&lt;/code&gt;. You'll have control over sbt console after executing that command, and to stop the API you can run &lt;code&gt;jetty:stop&lt;/code&gt;. Of course, &lt;code&gt;CTRL + C&lt;/code&gt; will work too, but that will close the sbt console too.&lt;/p&gt;

&lt;p&gt;You can test the API now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ curl http://localhost:8080/professionals-api/status
{"healthy":true}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great, stop the server now and we'll get back to coding.&lt;/p&gt;

&lt;h2&gt;
  
  
  Swagger Documentation
&lt;/h2&gt;

&lt;p&gt;Now we'll create the servlet that will return our endpoints documentation. &lt;/p&gt;

&lt;p&gt;First, we need to create a package called &lt;code&gt;com.svinci.professionals.api.domain.docs&lt;/code&gt;, and under that package we'll write a file called &lt;code&gt;DocsServlet.scala&lt;/code&gt; with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.svinci.professionals.api.domain.docs

import com.svinci.professionals.api.infrastructure.ProfessionalsApiSwagger
import org.scalatra.ScalatraServlet
import org.scalatra.swagger.NativeSwaggerBase

/**
  * This servlet, as is, will be able to return swagger v1 JSONs. This is the entry point to our documentation.
  */
class DocsServlet extends ScalatraServlet with NativeSwaggerBase {

  /**
    * Application swagger global instance.
    */
  override protected implicit def swagger = ProfessionalsApiSwagger

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a really simple servlet, so I didn't feel like doing cake pattern here, it didn't make sense. Now, in the &lt;code&gt;Module.scala&lt;/code&gt; object we'll need to add a new function to retrieve an instance of this servlet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  /**
    * Swagger documentation servlet instance.
    */
  def docsServlet: DocsServlet = new DocsServlet
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once we have everything in place, we mount the new servlet to the &lt;code&gt;ServletContext&lt;/code&gt; on &lt;code&gt;ScalatraBootstrap&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;context.mount(Module.docsServlet, "/docs", "docs")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now start our server again and test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
$ curl http://localhost:8080/docs
{"apiVersion":"1.0.0","swaggerVersion":"1.2","apis":[{"path":"/professionals-api/status","description":"API Status."}],"authorizations":{},"info":{}}

$ curl http://localhost:8080/docs/professionals-api/status
{"apiVersion":"1.0.0","swaggerVersion":"1.2","resourcePath":"/professionals-api/status","produces":["application/json"],"consumes":["application/json"],"protocols":["http"],"apis":[{"path":"/professionals-api/status/","operations":[{"method":"GET","summary":"Retrieve API status.","position":0,"notes":"","deprecated":false,"nickname":"status","parameters":[],"type":"Status"}]}],"models":{"Status":{"id":"Status","name":"Status","qualifiedType":"com.svinci.professionals.api.domain.status.Status","required":["healthy"],"properties":{"healthy":{"position":0,"type":"boolean"}}}},"basePath":"http://localhost:8080"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that general information of our API is found at &lt;code&gt;/docs&lt;/code&gt;, and then at &lt;code&gt;/docs/professionals-api/status&lt;/code&gt; you'll find documentation for the servlet that was mounted on &lt;code&gt;/professionals-api/status&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;That's it in this part of the post series. We have an API working, with a status endpoint and swagger documentation.&lt;/p&gt;

&lt;p&gt;Right now the second part hasn't been written, but in a couple days I'll have it done and I will put the link here.&lt;/p&gt;

&lt;p&gt;The code to this example can be found &lt;a href="https://github.com/svinci/scala-scalatra-swagger-example"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;See you in the comments!&lt;/p&gt;

</description>
      <category>scala</category>
      <category>rest</category>
      <category>swagger</category>
      <category>scalatra</category>
    </item>
    <item>
      <title>Hi, I'm Sebastian Vinci</title>
      <dc:creator>Sebastian G. Vinci</dc:creator>
      <pubDate>Sun, 16 Apr 2017 06:57:24 +0000</pubDate>
      <link>https://dev.to/svinci/hi-im-sebastian-vinci</link>
      <guid>https://dev.to/svinci/hi-im-sebastian-vinci</guid>
      <description>&lt;p&gt;I have been coding for 8 years.&lt;/p&gt;

&lt;p&gt;You can find me on GitHub as &lt;a href="https://github.com/svinci" rel="noopener noreferrer"&gt;svinci&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I live in Buenos Aires, Argentina.&lt;/p&gt;

&lt;p&gt;I mostly program in these languages: Java, Scala, Python and JavaScript.&lt;/p&gt;

&lt;p&gt;I am currently learning more about infrastructure as a code.&lt;/p&gt;

&lt;p&gt;Nice to meet you.&lt;/p&gt;

</description>
      <category>introduction</category>
    </item>
    <item>
      <title>Deploy using docker swarm</title>
      <dc:creator>Sebastian G. Vinci</dc:creator>
      <pubDate>Sun, 16 Apr 2017 06:42:39 +0000</pubDate>
      <link>https://dev.to/svinci/deploy-using-docker-swarm</link>
      <guid>https://dev.to/svinci/deploy-using-docker-swarm</guid>
      <description>&lt;p&gt;I just finished &lt;a href="https://dev.to/svinci/react-js-web-site-example-almost-real-life-like"&gt;this&lt;/a&gt; tutorial that shows how to build a web site using ReactJS and Redux. For testing purposes I also showed how to build a REST API using nodeJS.&lt;/p&gt;

&lt;p&gt;Now, let's deploy those two using docker swarm.&lt;/p&gt;

&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;

&lt;p&gt;First of all, you'll need to clone the React tutorial repository from &lt;a href="https://github.com/svinci/react-example"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now, you'll need to install Docker. Installation instructions can be found &lt;a href="https://www.docker.com/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Once you have docker running, you need to restart the docker daemon to make it run in swarm mode. This can be achieved by running the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ docker swarm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you're good to go.&lt;/p&gt;

&lt;h2&gt;
  
  
  Docker Images
&lt;/h2&gt;

&lt;p&gt;Now we'll need to write the docker images for our API and our UI. &lt;/p&gt;

&lt;h3&gt;
  
  
  API Image
&lt;/h3&gt;

&lt;p&gt;Let's start with the API. Here's the Dockerfile for our NodeJS API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM node:boron

RUN mkdir -p /usr/src/app/config
WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN npm install

COPY config/default.json /usr/src/app/config/default.json
COPY index.js /usr/src/app/index.js

EXPOSE 8100

CMD ["npm", "run", "start"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are building our image from &lt;code&gt;node:boron&lt;/code&gt; (NodeJS 6). Then we're creating a directory in &lt;code&gt;/usr/src/app&lt;/code&gt; to deploy the API there, copying the &lt;code&gt;package.json&lt;/code&gt; there and installing dependencies.&lt;/p&gt;

&lt;p&gt;Then we copy the configuration and our index.js file. We expose port 8100 and start the server.&lt;/p&gt;

&lt;p&gt;Now we build the image running &lt;code&gt;docker build -t svinci/todo-api .&lt;/code&gt;. Feel free to change the namespace.&lt;/p&gt;

&lt;h3&gt;
  
  
  UI Image
&lt;/h3&gt;

&lt;p&gt;Now, the UI will be a little more tricky. The container has to deploy an NGINX to work as a web server of the UI, and it has to have the rules to acces the API passing through it.&lt;/p&gt;

&lt;p&gt;Let's start by making a directory called &lt;code&gt;conf&lt;/code&gt; that will hold NGINX configuration. In it we'll write a file called &lt;code&gt;nginx.conf&lt;/code&gt; with the following content.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections 1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '[$remote_addr] [$time_local] [$request] '
                      'status code: $status, response size: $body_bytes_sent, referer: "$http_referer", '
                      'user agent: "$http_user_agent", $request_time seconds';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;

    keepalive_timeout  65;

    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;

    include /etc/nginx/conf.d/*.conf;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This basically sets the queue size, mime types, access log format and gzip. Now, in a subdirectory of &lt;code&gt;conf&lt;/code&gt; called &lt;code&gt;conf.d&lt;/code&gt;, we'll write the following in a file called &lt;code&gt;default.conf&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server {
    listen       80;
    server_name  localhost;

    location /todos {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://api:8100;
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This sets the listening port to 80, configures a proxy pass to the API and sets the site entry point.&lt;/p&gt;

&lt;p&gt;Now, with this done, here's the Dockerfile.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM nginx

COPY conf /etc/nginx

COPY index.html /usr/share/nginx/html
COPY bundle.js /usr/share/nginx/html

EXPOSE 80
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are building our image from &lt;code&gt;nginx&lt;/code&gt;, copying our NGINX configuration, and copying our bundle and our index.html to the default static content location for the web server. Then we expose the port 80.&lt;/p&gt;

&lt;p&gt;Now, before actually building the docker image, we have to do a tiny modification. This example was meant to be run locally, so we need to modify the file under &lt;code&gt;todo-site/src/client.js&lt;/code&gt; to change &lt;code&gt;http://localhost:8100/todos&lt;/code&gt; by just &lt;code&gt;/todos&lt;/code&gt; so the UI executes the requests through our NGINX. It should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as superagent from "superagent";

export function get() {

    return new Promise((resolve, reject) =&amp;gt; {
        superagent.get("/todos")
            .end((error, result) =&amp;gt; {
                error ? reject(error) : resolve(result.body);
            });
    });

}

export function add(text) {

    return new Promise((resolve, reject) =&amp;gt; {
        superagent.post("/todos")
            .send({'text': text})
            .end((error, result) =&amp;gt; {
                error ? reject(error) : resolve(result.body);
            });
    });

}

export function toggle(id) {

    return new Promise((resolve, reject) =&amp;gt; {
        superagent.patch("/todos/" + id)
            .end((error, result) =&amp;gt; {
                error ? reject(error) : resolve(result.body);
            });
    });

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we build the image running &lt;code&gt;npm install &amp;amp;&amp;amp; npm run build &amp;amp;&amp;amp; docker build -t svinci/todo-site .&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Compose
&lt;/h2&gt;

&lt;p&gt;We now have to write our compose file. This file defines all the services we need running, with its dependencies, replication factor, networks and stuff. &lt;/p&gt;

&lt;p&gt;We need to write the below content into a file called &lt;code&gt;compose.yml&lt;/code&gt; on the root of the repository.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: "3"

services:
  api:
    image: svinci/todo-api
    networks:
      - todo_network
    ports:
      - 8100
    deploy:
      replicas: 1
      update_config:
        parallelism: 1
      restart_policy:
        condition: on-failure
  site:
    image: svinci/todo-site
    ports:
      - 80:80
    networks:
      - todo_network
    depends_on:
      - api
    deploy:
      replicas: 1
      update_config:
        parallelism: 1
      restart_policy:
        condition: on-failure

networks:
  todo_network:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are defining two services here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;api: The To Do REST API.&lt;/li&gt;
&lt;li&gt;site: Our NGINX with the static content.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you see, we are setting the images it needs to use, and the network they belong to. &lt;/p&gt;

&lt;p&gt;We are also defining that the site depends on the API to work. &lt;/p&gt;

&lt;p&gt;Deployment configuration is being provided too. Notice the &lt;code&gt;replicas&lt;/code&gt; under &lt;code&gt;deploy&lt;/code&gt; for each service, we could have redundancy here out of the box. &lt;/p&gt;

&lt;h2&gt;
  
  
  Deploy
&lt;/h2&gt;

&lt;p&gt;Now, let's deploy this. To deploy we need to run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker stack deploy --compose-file=compose.yml todo_stack
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you visit &lt;code&gt;http://localhost/&lt;/code&gt; in your browser after a couple seconds (NGINX takes like 15 seconds to start), you'll see the site fully working.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;It's fairly easy to dockerize stuff, and I really prefer to work this way as I don't need to install too much software on my computer (NGINX for example). Also, if you deploy like this in production, your local environment will ressemble production a lot, which is awesome.&lt;/p&gt;

&lt;p&gt;You can find the source code of this example &lt;a href="https://github.com/svinci/react-example"&gt;here&lt;/a&gt; on a branch called &lt;code&gt;docker-swarm&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;See you in the comments!&lt;/p&gt;

</description>
      <category>docker</category>
      <category>swarm</category>
      <category>compose</category>
    </item>
    <item>
      <title>React JS Web Site Example (Almost like real life).</title>
      <dc:creator>Sebastian G. Vinci</dc:creator>
      <pubDate>Sun, 16 Apr 2017 04:44:58 +0000</pubDate>
      <link>https://dev.to/svinci/react-js-web-site-example-almost-real-life-like</link>
      <guid>https://dev.to/svinci/react-js-web-site-example-almost-real-life-like</guid>
      <description>&lt;p&gt;I've been trying to use react on my personal projects for a couple weeks now, but I found out that there isn't one example on the internet (that I could find) that ressembles what I want in a real life scenario.&lt;/p&gt;

&lt;p&gt;Asynchronous HTTP requests, loading animations, error pages, etc. None of those things are covered by one concise example that can be found on the first two pages of google.&lt;/p&gt;

&lt;p&gt;Having said that, I took one &lt;a href="https://www.sitepoint.com/how-to-build-a-todo-app-using-react-redux-and-immutable-js/"&gt;example&lt;/a&gt; that took me far enough, and started researching and building on top of it.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are we going to do?
&lt;/h2&gt;

&lt;p&gt;We are going to build a simple To Do List web application.&lt;/p&gt;

&lt;p&gt;To do this, we are going to build a very simple REST API in Node.js using &lt;a href="https://www.npmjs.com/package/rest-api-starter"&gt;rest-api-starter&lt;/a&gt;, and a web site based on React.JS, Redux and Bootstrap.&lt;/p&gt;

&lt;h2&gt;
  
  
  What am I going to need to follow this tutorial?
&lt;/h2&gt;

&lt;p&gt;First, a Node.js 6 installation, an IDE and a browser (which you probably have already, as you are reading this). Instructions on how to install Node.js can be found &lt;a href="https://nodejs.org/en/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Second, a Python 2.7 installation. If you are on a Mac OS or an Ubuntu based system, you already have it. Instructions on how to install Python can be found &lt;a href="https://www.python.org/downloads/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;All the commands I'll provide to install, run and do stuff were tested on Linux Mint 18. They'll probably work on Mac OS without any issue. If you're working on windows I'm really sorry.&lt;/p&gt;

&lt;h2&gt;
  
  
  Can we start coding already?
&lt;/h2&gt;

&lt;p&gt;Allright, first of all, let's make our directories.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mkdir todo-api
$ mkdir todo-site
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  API project
&lt;/h3&gt;

&lt;p&gt;Now, let's start with the API. We are going to &lt;code&gt;cd&lt;/code&gt; to the API directory, and run &lt;code&gt;npm init&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ cd todo-api
$ npm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can leave all the defaults.&lt;/p&gt;

&lt;p&gt;Now we have a node project there, we are going to install &lt;code&gt;rest-api-starter&lt;/code&gt; and &lt;code&gt;uuid&lt;/code&gt; (for id generation and stuff).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm install --save rest-api-starter uuid
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, &lt;code&gt;rest-api-starter&lt;/code&gt; requires a tiny configuration file on a subdirectory called &lt;code&gt;config&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mkdir config
$ cd config &amp;amp;&amp;amp; touch default.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;config/default.json&lt;/code&gt; file should look exactly like the one below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "app": {
    "http": {
      "port": 8100,
      "host": "0.0.0.0",
      "queue": 10,
      "secret": "",
      "transactionHeader": "X-REST-TRANSACTION"
    },
    "log": {
      "level": "info",
      "transports": [
        {
          "type": "console"
        }
      ]
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's code our rest API. We need CORS support to be able to easily develop on our local environment and three handlers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;POST &lt;code&gt;/todos&lt;/code&gt;: Create an item.&lt;/li&gt;
&lt;li&gt;GET &lt;code&gt;/todos&lt;/code&gt;: Retrieve all items.&lt;/li&gt;
&lt;li&gt;PATCH &lt;code&gt;/todos/:id&lt;/code&gt;: Mark an item as done or undone.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also, an OPTIONS handler for each path should be implemented for CORS support. So, our &lt;code&gt;index.js&lt;/code&gt; file will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const uuid = require('uuid');
const serveBuilder = require('rest-api-starter').server;
const todos = [];

const router = (app) =&amp;gt; {

    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, OPTIONS");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });

    app.options('/todos', (request, response) =&amp;gt; response.status(200).send());

    app.post('/todos', (request, response) =&amp;gt; {
        const todo = {
            'id': uuid.v4(),
            'isDone': false,
            'text': request.body.text
        };
        todos.push(todo);
        response.send(todo);
    });

    app.get('/todos', (request, response) =&amp;gt; {
        response.send(todos);
    });

    app.options('/todos/:id', (request, response) =&amp;gt; response.status(200).send());

    app.patch('/todos/:id', (request, response) =&amp;gt; {
        let result = null;
        todos.forEach((todo) =&amp;gt; {
            if (todo.id === request.params.id) {
                todo.isDone = !todo.isDone;
                result = todo;
            }
        });

        if (!result) {
            response.status(404).send({'msg': 'todo not found'});
        } else {
            response.send(result);
        }
    });

};

serveBuilder(router);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, add &lt;code&gt;"start": "node index.js"&lt;/code&gt; to the &lt;code&gt;scripts&lt;/code&gt; section of your package.json file to start the server. By running &lt;code&gt;npm run start&lt;/code&gt; on the root of the API project, you'll have your server listening on &lt;code&gt;http://localhost:8100&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Site project
&lt;/h3&gt;

&lt;p&gt;Now we're going to cd to the site project and run an &lt;code&gt;npm init&lt;/code&gt; there. Defaults are fine here too.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ cd todo-site
$ npm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now, we install the dependencies we need:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm install --save babel-core babel-loader babel-preset-es2015 babel-preset-react bootstrap jquery superagent webpack react react-dom react-redux redux redux-thunk style-loader css-loader
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Webpack
&lt;/h4&gt;

&lt;p&gt;We'll be using webpack to transpile and unify all the code into una file called &lt;code&gt;bundle.js&lt;/code&gt;, so it will be convenient to add &lt;code&gt;"build": "webpack --debug"&lt;/code&gt; and &lt;code&gt;"serve": "npm run build &amp;amp;&amp;amp; python -m SimpleHTTPServer 8080"&lt;/code&gt; to the scripts section in our package.json.&lt;/p&gt;

&lt;p&gt;Now we'll need a &lt;code&gt;webpack.config.js&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const webpack = require('webpack');

module.exports = {
    entry: {
        main: './src/app.js'
    },
    output: {
        path: __dirname,
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: { presets: [ 'es2015', 'react' ] }
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            },
            {
                test: /\.(png|jpg|gif|ttf|svg|woff|woff2|eot)$/,
                loader: "url-loader"
            }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            bootstrap: "bootstrap"
        })
    ]
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This webpack configuration transpiles all the javascript files that are using ES6 and JSX, and then puts them together, with all their dependencies, in one big file called &lt;code&gt;bundle.js&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;If any stylesheet is required from &lt;code&gt;src/app.js&lt;/code&gt;, it will import it and add it to the bundle (following any imports made from the stylesheets) and the generated bundle script will add a &lt;code&gt;&amp;lt;style&amp;gt;&lt;/code&gt; tag to the HTML.&lt;/p&gt;

&lt;p&gt;It also uses the &lt;code&gt;ProvidePlugin&lt;/code&gt; to expose JQuery and bootstrap, so we can forget about importing them.&lt;/p&gt;

&lt;h4&gt;
  
  
  Stylesheets
&lt;/h4&gt;

&lt;p&gt;Now, let's start with some structure. Let's create a directory called &lt;code&gt;css&lt;/code&gt; in the root of the project and add the following &lt;code&gt;app.css&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That stylesheet just imports bootstrap, but you can add custom style and import any stylesheet you want there. That should be the entrypoint for all the stylesheets in the project.&lt;/p&gt;

&lt;h4&gt;
  
  
  HTML. Site entrypoint.
&lt;/h4&gt;

&lt;p&gt;Then, we create our &lt;code&gt;index.html&lt;/code&gt; in the project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
        &amp;lt;title&amp;gt;Todo List&amp;lt;/title&amp;gt;

        &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;div id="app"&amp;gt;&amp;lt;/div&amp;gt;

        &amp;lt;script src="bundle.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a pretty simple HTML file. It has a title, the viewport recommended by bootstrap, a &lt;code&gt;div&lt;/code&gt; with the id &lt;code&gt;app&lt;/code&gt; and the import of our bundle.&lt;/p&gt;

&lt;p&gt;That div called &lt;code&gt;app&lt;/code&gt; will be our application container. We'll tell react to render its components there.&lt;/p&gt;

&lt;h4&gt;
  
  
  React Components
&lt;/h4&gt;

&lt;p&gt;Let's write our React.js components. A React component is an independent piece of code that receives some props and renders HTML from that props. It should JUST be React, a component's code should know nothing about Redux. Just presentation. (I can't stress this enough).&lt;/p&gt;

&lt;p&gt;Create a directory called &lt;code&gt;src&lt;/code&gt; on the root of the project, and write the code below to a file named &lt;code&gt;components.js&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

function Todo(props) {
    const { todo } = props;
    if (todo.isDone) {
        return &amp;lt;del&amp;gt;{todo.text}&amp;lt;/del&amp;gt;
    } else {
        return &amp;lt;span&amp;gt;{todo.text}&amp;lt;/span&amp;gt;
    }
}

function TodoList(props) {

    const { todos, toggleTodo, addTodo } = props;

    const onSubmit = (event) =&amp;gt; {
        event.preventDefault();

        const textInput = document.getElementById('todo-input');

        const text = textInput.value;

        if (text &amp;amp;&amp;amp; text.length &amp;gt; 0) {
            addTodo(text);
        }

        textInput.value = '';
    };

    const toggleClick = id =&amp;gt; event =&amp;gt; toggleTodo(id);

    return (
        &amp;lt;div className='todo-list-container'&amp;gt;
            &amp;lt;div className="panel panel-default"&amp;gt;
                &amp;lt;div className="panel-body"&amp;gt;
                    &amp;lt;form onSubmit={onSubmit}&amp;gt;
                        &amp;lt;div className="form-group"&amp;gt;
                            &amp;lt;label&amp;gt;To Do Text: &amp;lt;/label&amp;gt;
                            &amp;lt;input id="todo-input" type='text'
                                   className='todo-input form-control'
                                   placeholder='Add todo' /&amp;gt;
                        &amp;lt;/div&amp;gt;
                        &amp;lt;button type="submit" className="btn btn-default"&amp;gt;Submit&amp;lt;/button&amp;gt;
                    &amp;lt;/form&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
            {
                todos.length &amp;gt; 0 ?
                    &amp;lt;div className='todo-list list-group'&amp;gt;
                        {todos.map(t =&amp;gt; (
                            &amp;lt;a key={t.id}
                                className='todo-list-item list-group-item'
                                onClick={toggleClick(t.id)}&amp;gt;
                                &amp;lt;Todo todo={t} /&amp;gt;
                            &amp;lt;/a&amp;gt;
                        ))}
                    &amp;lt;/div&amp;gt; :
                    &amp;lt;div className="alert alert-info" role="alert"&amp;gt;ToDo list is empty.&amp;lt;/div&amp;gt;
            }
        &amp;lt;/div&amp;gt;
    );
}

function Layout(props) {
    return (
        &amp;lt;div className='container'&amp;gt;
            &amp;lt;div className='row'&amp;gt;
                &amp;lt;div className='col-lg-6 col-lg-offset-3'&amp;gt;
                    &amp;lt;div className='page-header'&amp;gt;
                        &amp;lt;h1&amp;gt;To Do List &amp;lt;small&amp;gt;Keep it organized.&amp;lt;/small&amp;gt;&amp;lt;/h1&amp;gt;
                    &amp;lt;/div&amp;gt;
                    {props.children}
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

function ProgressBar(props) {
    const { completed } = props;

    const style = { 'width': completed + '%'};

    return (
        &amp;lt;div className="progress"&amp;gt;
            &amp;lt;div className="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow={completed} aria-valuemin='0' aria-valuemax='100' style={style}&amp;gt;
                &amp;lt;span className="sr-only"&amp;gt;{completed}% Complete&amp;lt;/span&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

export function TodoPage(props) {

    const {state, toggleTodo, addTodo, retrieveTodos } = props;

    if (state.error) {
        return (
            &amp;lt;Layout&amp;gt;
                &amp;lt;div className="alert alert-danger" role="alert"&amp;gt;{state.error.toString()}&amp;lt;/div&amp;gt;
                &amp;lt;input className='retry-button btn btn-default' type='button' value='Retry' onClick={retrieveTodos}/&amp;gt;
            &amp;lt;/Layout&amp;gt;
        );
    } else if (state.initialized) {
        return (
            &amp;lt;Layout&amp;gt;
                &amp;lt;TodoList todos={state.todos} toggleTodo={toggleTodo} addTodo={addTodo} /&amp;gt;
            &amp;lt;/Layout&amp;gt;
        )
    } else {
        retrieveTodos();
        return (
            &amp;lt;Layout&amp;gt;
                &amp;lt;ProgressBar completed="45"/&amp;gt;
            &amp;lt;/Layout&amp;gt;
        );
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's our presentation layer. We export one function, called &lt;code&gt;TodoPage&lt;/code&gt;, which uses some components only available inside the module.&lt;/p&gt;

&lt;p&gt;These components receive the application's state, and three actions: toggleTodo, addTodo, retrieveTodos. The components don't know what they do, they just know how to invoke them, and they don't even care about a return value.&lt;/p&gt;

&lt;p&gt;Notice that the components receive the state and the actions, and just cares about how the state is displayed, and how are those actions mapped to HTML events.&lt;/p&gt;

&lt;h4&gt;
  
  
  API Client
&lt;/h4&gt;

&lt;p&gt;Now, let's write our API client using &lt;code&gt;superagent&lt;/code&gt; and ES6 promises. under a directory called &lt;code&gt;src&lt;/code&gt; created on the root of our project write the following code on a file called &lt;code&gt;client.js&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as superagent from "superagent";

export function get() {

    return new Promise((resolve, reject) =&amp;gt; {
        superagent.get("http://localhost:8100/todos")
            .end((error, result) =&amp;gt; {
                error ? reject(error) : resolve(result.body);
            });
    });

}

export function add(text) {

    return new Promise((resolve, reject) =&amp;gt; {
        superagent.post("http://localhost:8100/todos")
            .send({'text': text})
            .end((error, result) =&amp;gt; {
                error ? reject(error) : resolve(result.body);
            });
    });

}

export function toggle(id) {

    return new Promise((resolve, reject) =&amp;gt; {
        superagent.patch("http://localhost:8100/todos/" + id)
            .end((error, result) =&amp;gt; {
                error ? reject(error) : resolve(result.body);
            });
    });

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That module exports three functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;get: Executes a GET request to &lt;code&gt;/todos&lt;/code&gt; in our API to retrieve all To Do items.&lt;/li&gt;
&lt;li&gt;add: Executes a POST request to &lt;code&gt;/todos&lt;/code&gt; in our API to add a To Do item.&lt;/li&gt;
&lt;li&gt;toggle: Executes a PATCH request to &lt;code&gt;/todos/:id&lt;/code&gt; to change the &lt;code&gt;isDone&lt;/code&gt; flag of that item.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Redux Actions
&lt;/h4&gt;

&lt;p&gt;Let's talk about actions...&lt;/p&gt;

&lt;p&gt;Actions, in Redux, are pieces of information that get sent to the store. These payloads trigger modifications on the state of the application. &lt;/p&gt;

&lt;p&gt;Actions are basically Redux's way of saying "Hey! This happened!".&lt;/p&gt;

&lt;p&gt;&lt;em&gt;WARNING&lt;/em&gt;: Not actual modifications, the state of the application shoud be treated as an immutable object. You should never modify the state, but copy it, change the copy and keep going. More on it further down.&lt;/p&gt;

&lt;p&gt;Actions are generated via action builders. These builders are functions that get invoked with some information and return the action, which is sent to the store via a &lt;code&gt;dispatch&lt;/code&gt; function provided by Redux.&lt;/p&gt;

&lt;p&gt;An interesting concept, necessary for real world applications, are asynchronous actions. These aren't actually just a piece of information, but another function that receives the &lt;code&gt;dispatch&lt;/code&gt; function as parameters and, after some asynchronous operations, dispatches another action. Let's explain it with some code.&lt;/p&gt;

&lt;p&gt;Write the following code on a file called &lt;code&gt;actions.js&lt;/code&gt; under the &lt;code&gt;src&lt;/code&gt; directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { get, add, toggle } from './client';

export function addTodo(text) {
    return (dispatch) =&amp;gt; {
        add(text)
            .then(get)
            .then((todos) =&amp;gt; dispatch(receiveTodos(todos)))
            .catch((err) =&amp;gt; dispatch(error(err)));
    };
}

export function toggleTodo(id) {
    return (dispatch) =&amp;gt; {
        toggle(id)
            .then(get)
            .then((todos) =&amp;gt; dispatch(receiveTodos(todos)))
            .catch((err) =&amp;gt; dispatch(error(err)));
    };
}

export function retrieveTodos() {
    return (dispatch) =&amp;gt; get()
        .then((todos) =&amp;gt; dispatch(receiveTodos(todos)))
        .catch((err) =&amp;gt; dispatch(error(err)))
}

function receiveTodos(todos) {
    return {
        type: 'RECEIVE_TODOS',
        payload: todos
    }
}

function error(err) {
    return {
        type: 'ERROR',
        payload: err
    };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We here are defining all the behavior of our application. &lt;/p&gt;

&lt;p&gt;Our application has to retrieve To Do items from the API, toggle them and create them. These actions are asynchronows. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The addTodo action builder returns an asynchronous action that, after posting a new To Do item to the API, and retrieving all the To Do items again, dispatches the &lt;code&gt;receiveTodos&lt;/code&gt; action. On error, it dispatches the &lt;code&gt;error&lt;/code&gt; action.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The toggleTodo action builder returns an asynchronous action that, after toggling the To Do item on the API, and retrieving all the items again, dispatches the &lt;code&gt;receiveTodos&lt;/code&gt; action. On error, it dispatches the &lt;code&gt;error&lt;/code&gt; action.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The retrieveTodos action builder returns an asynchronous action that, after retrieving all the To Do items from the API, dispatches the &lt;code&gt;receiveTodos&lt;/code&gt; action. On error, it dispatches the &lt;code&gt;error&lt;/code&gt; action.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Notice that these (not as they are defined here, we'll see how) are the actions that are used by our components to handle HTML events.&lt;/p&gt;

&lt;p&gt;The other two actions are ordinary actions, that receive some data and returns a payload.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The receiveTodos action builder returns an action of type &lt;code&gt;RECEIVE_TODOS&lt;/code&gt; with the retrieved todos as payload.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The error action builder returns an action of type &lt;code&gt;ERROR&lt;/code&gt; with the received error as payload.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This might sound confusing. I think Redux is not an easy to understand state manager, its concepts are pretty hard to understand, but if you put this in practice and read the code you'll end up liking it a lot.&lt;/p&gt;

&lt;h4&gt;
  
  
  Redux Reducer
&lt;/h4&gt;

&lt;p&gt;This takes us to the reducers. A reducer is a function that receives the current state of the application and an action. As stated before, an action is a way of saying that something happened, and a reducer grabs that event/information and does what it need to do to the state to impact that event on it.&lt;/p&gt;

&lt;p&gt;Basically, they receive the current state of the application and an action that was performed (an event or something, like a user click for example) and return the new state of the application.&lt;/p&gt;

&lt;p&gt;Let's see more code. Write the following code on a file called &lt;code&gt;reducer.js&lt;/code&gt; under the &lt;code&gt;src&lt;/code&gt; directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const init = {'todos': [], 'error': false};

export default function(state=init, action) {
    switch(action.type) {
        case 'RECEIVE_TODOS':
            return {'todos': action.payload, 'error': false, 'initialized': true};
        case 'ERROR':
            return {'todos': [], 'error': action.payload, 'initialized': true};
        default:
            return state;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This reducer is defining the initial state of the application and taking care of handling the actions it receives.&lt;/p&gt;

&lt;p&gt;If the action it received is of type &lt;code&gt;RECEIVE_TODOS&lt;/code&gt;, it returns the new state, ensuring that &lt;code&gt;error&lt;/code&gt; is false, &lt;code&gt;initialized&lt;/code&gt; is true and &lt;code&gt;todos&lt;/code&gt; contains the received todos.&lt;/p&gt;

&lt;p&gt;If the action it received is of type &lt;code&gt;ERROR&lt;/code&gt;, it returns the new state, ensuring that &lt;code&gt;error&lt;/code&gt; contains the ocurred error, &lt;code&gt;initialized&lt;/code&gt; is true and &lt;code&gt;todos&lt;/code&gt; is an empty array.&lt;/p&gt;

&lt;p&gt;If the action it received has no handler, it just passes through the current state of the application as no changes are to be applied.&lt;/p&gt;

&lt;p&gt;Sorry I repeat myself so much, but this concept took me a while: React components receive Redux's action builders, and ivoke them on HTML events. These events get dispatched to Redux's reducers to do what they have to do to the state based on the information provided by the action.&lt;/p&gt;

&lt;h4&gt;
  
  
  Container Components
&lt;/h4&gt;

&lt;p&gt;Another new concept: containers. Containers are a type of component, they are called &lt;code&gt;Container Components&lt;/code&gt;. They do the connection between React components (which are just presentational components and know nothing about redux), and redux's actions and state.&lt;/p&gt;

&lt;p&gt;They basically wrap the react component, and grabs the state and the actions and maps them to props. &lt;/p&gt;

&lt;p&gt;Let's see the code. Write the following code in a file called &lt;code&gt;containers.js&lt;/code&gt; under the &lt;code&gt;src&lt;/code&gt; directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { connect } from 'react-redux';
import * as components from './components';
import { addTodo, toggleTodo, retrieveTodos } from './actions';

export const TodoPage = connect(
    function mapStateToProps(state) {
        return { state: state };
    },
    function mapDispatchToProps(dispatch) {
        return {
            addTodo: text =&amp;gt; dispatch(addTodo(text)),
            toggleTodo: id =&amp;gt; dispatch(toggleTodo(id)),
            retrieveTodos: () =&amp;gt; dispatch(retrieveTodos())
        };
    }
)(components.TodoPage);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It grabs our &lt;code&gt;TodoPage&lt;/code&gt;, our actions and the state, and puts them into props, for our component to see. This is where everything is glued together.&lt;/p&gt;

&lt;h4&gt;
  
  
  Web Application Start Up
&lt;/h4&gt;

&lt;p&gt;Let's go to our application entry point now. Write the following code in a file called &lt;code&gt;app.js&lt;/code&gt; under &lt;code&gt;src&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import '../css/app.css';

import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import reducer from './reducer';
import { TodoPage } from './containers';

const store = createStore(reducer, applyMiddleware(thunk));

document.addEventListener("DOMContentLoaded", function() {

    render(
        &amp;lt;Provider store={store}&amp;gt;
            &amp;lt;TodoPage /&amp;gt;
        &amp;lt;/Provider&amp;gt;,
        document.getElementById('app')
    );

});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This file is importing our css entry point file, our reducer and the TodoPage container (not the component, the container).&lt;/p&gt;

&lt;p&gt;Then, it creates the Redux store (basically, where te state lives). You might have noticed that our reducer is not handling any of our asynchronous actions, thats why we are passing that &lt;code&gt;applyMiddleware(thunk)&lt;/code&gt; to &lt;code&gt;createStore&lt;/code&gt;. &lt;code&gt;redux-thunk&lt;/code&gt; takes care of handling asynchronous actions just like that.&lt;/p&gt;

&lt;p&gt;We now wait for the DOM to be loaded, and then calling React's &lt;code&gt;render&lt;/code&gt; function. This function receives a component and the container HTML element (that's our div#app from index.html).&lt;/p&gt;

&lt;p&gt;The component we are passing to the &lt;code&gt;render&lt;/code&gt; function is a &lt;code&gt;Provider&lt;/code&gt; tag, with &lt;em&gt;only one child&lt;/em&gt; (this is important, it can not have more than one child), which is our &lt;code&gt;TodoPage&lt;/code&gt; container component. We are passing our store to the &lt;code&gt;Provider&lt;/code&gt; tag by the way.&lt;/p&gt;

&lt;h4&gt;
  
  
  You're ready to go
&lt;/h4&gt;

&lt;p&gt;We now can run &lt;code&gt;npm run serve&lt;/code&gt; in the root of the site project, and &lt;code&gt;npm run start&lt;/code&gt; in the root of the API project. Now we can visit &lt;code&gt;http://localhost:8080/&lt;/code&gt; and use our To Do list.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;I find this pair (React, Redux) to have a pretty complex ramp up, but once you get the hang of it, applications are written quickly and the code looks great too. Yeah, it's a lot of boiler plate sometimes, but it looks nice and it actually performs pretty well too.&lt;/p&gt;

&lt;p&gt;I come from the JQuery world, then moved on to Angular.JS, and now I moved to React.JS and Redux and I actually like it.&lt;/p&gt;

&lt;p&gt;You can find the code to this example &lt;a href="https://github.com/svinci/react-example"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;See you in the comments!&lt;/p&gt;

</description>
      <category>react</category>
      <category>redux</category>
      <category>javascript</category>
      <category>node</category>
    </item>
  </channel>
</rss>
