<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ REST - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ REST - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 05:06:16 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/rest/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ OpenFeign vs WebClient: How to Choose a REST Client for Your Spring Boot Project ]]>
                </title>
                <description>
                    <![CDATA[ When building microservices with Spring Boot, you’ll have to decide how the services will communicate with one another. The basic choices in terms of protocols are Messaging and REST. In this article we’ll discuss tools based on REST, which is a comm... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/best-choice-openfeign-or-webclient/</link>
                <guid isPermaLink="false">6841f2c63a801418642db429</guid>
                
                    <category>
                        <![CDATA[ spring-boot ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Microservices ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mario Casari ]]>
                </dc:creator>
                <pubDate>Thu, 05 Jun 2025 19:40:54 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749152217156/dc3e8896-b084-4bec-a549-b51a821f7d69.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When building microservices with Spring Boot, you’ll have to decide how the services will communicate with one another. The basic choices in terms of protocols are Messaging and <a target="_blank" href="https://www.freecodecamp.org/news/tag/rest-api/">REST</a>. In this article we’ll discuss tools based on REST, which is a common protocol for microservices. Two well-known tools are <a target="_blank" href="https://codingstrain.com/rest-clients-with-openfeign-how-to-implement-them/"><strong>OpenFeign</strong></a> and <a target="_blank" href="https://docs.spring.io/spring-framework/reference/web/webflux-webclient.html"><strong>WebClient</strong></a>.</p>
<p>You’ll learn how they differ in their approaches, use cases, and design. You’ll then have the necessary information to make a proper choice.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-introduction-to-openfeign">Introduction to OpenFeign</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-introduction-to-webclient">Introduction to WebClient</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-main-differences">Main Differences</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-performance-considerations">Performance Considerations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-cases">Use Cases</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-introduction-to-openfeign">Introduction to OpenFeign</h2>
<p>OpenFeign is an HTTP client tool developed originally by Netflix and now maintained as an open-source community project. In the Spring Cloud ecosystem, OpenFeign allows you to define REST clients using annotated Java interfaces, reducing boilerplate code.</p>
<p>A basic OpenFeign client looks like this:</p>
<pre><code class="lang-java"><span class="hljs-meta">@FeignClient(name = "book-service")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">BookClient</span> </span>{
    <span class="hljs-meta">@GetMapping("/books/{id}")</span>
    <span class="hljs-function">User <span class="hljs-title">getBookById</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable("id")</span> Long id)</span></span>;
}
</code></pre>
<p>You can then inject <code>BookClient</code> like any Spring Bean:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BookService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> BookClient bookClient;

    <span class="hljs-function"><span class="hljs-keyword">public</span> User <span class="hljs-title">getBook</span><span class="hljs-params">(Long id)</span> </span>{
        <span class="hljs-keyword">return</span> bookClient.getBookById(id);
    }
}
</code></pre>
<p>OpenFeign is well integrated with Spring Cloud Discovery Service (Eureka), Spring Cloud Config, and Spring Cloud LoadBalancer. This makes it perfect for service-to-service calls in a microservice architecture based on Spring Cloud. It has several important features.</p>
<ul>
<li><p>Declarative syntax: It uses interfaces and annotations to define HTTP clients, avoiding manual request implementation.</p>
</li>
<li><p>Spring Cloud integration: It integrates well with the components of Spring Cloud, like Service Discovery (Eureka), Spring Config, and Load Balancer.</p>
</li>
<li><p>Retry and fallback mechanisms: It can be easily integrated with Spring Cloud Circuit Breaker or Resilience4j.</p>
</li>
<li><p>Custom configurations: You can customize many aspects, like headers, interceptors, logging, timeouts, and encoders/decoders.</p>
</li>
</ul>
<h2 id="heading-introduction-to-webclient">Introduction to WebClient</h2>
<p>WebClient is a reactive HTTP client, and it’s part of the <a target="_blank" href="https://medium.com/@bolot.89/an-introduction-to-spring-webflux-reactive-programming-made-easy-f70050f4c6c6"><strong>Spring WebFlux</strong></a> module. It is mainly based on non-blocking asynchronous HTTP communication, but it can also deal with synchronous calls.</p>
<p>While OpenFeign follows a declarative design, WebClient offers an imperative, fluent API.</p>
<p>Here’s a basic example of using WebClient synchronously:</p>
<pre><code class="lang-java">WebClient client = WebClient.create(<span class="hljs-string">"http://book-service"</span>);

User user = client.get()
        .uri(<span class="hljs-string">"/books/{id}"</span>, <span class="hljs-number">1L</span>)
        .retrieve()
        .bodyToMono(Book.class)
        .block(); <span class="hljs-comment">// synchronous</span>
</code></pre>
<p>Or asynchronously:</p>
<pre><code class="lang-java">Mono&lt;User&gt; bookMono = client.get()
        .uri(<span class="hljs-string">"/books/{id}"</span>, <span class="hljs-number">1L</span>)
        .retrieve()
        .bodyToMono(Book.class);
</code></pre>
<p>Being designed to be non-blocking and reactive, WebClient gives its best with high-throughput, I/O intensive operations. This is particularly true if the entire stack is reactive.</p>
<h2 id="heading-main-differences">Main Differences</h2>
<h3 id="heading-programming-model">Programming Model</h3>
<ul>
<li><p><strong>OpenFeign</strong>: Declarative. You just have to define interfaces. The framework will provide implementations of those interfaces.</p>
</li>
<li><p><strong>WebClient</strong>: Programmatic. You use an imperative, fluent API to implement HTTP calls.</p>
</li>
</ul>
<h3 id="heading-synchronousasynchronous-calls">Synchronous/Asynchronous Calls</h3>
<ul>
<li><p><strong>OpenFeign</strong>: Based on synchronous calls. You require customization or third-party extensions to implement asynchronous behavior.</p>
</li>
<li><p><strong>WebClient</strong>: Asynchronous and non-blocking. It fits well with systems based on a reactive stack.</p>
</li>
</ul>
<h3 id="heading-integration-with-spring-cloud">Integration with Spring Cloud</h3>
<ul>
<li><p><strong>OpenFeign</strong>: It integrates well with the Spring Cloud stack, such as service discovery (Eureka), client-side load balancing, and circuit breakers.</p>
</li>
<li><p><strong>WebClient</strong>: It integrates with Spring Cloud, but additional configuration is required for some features, like load balancing.</p>
</li>
</ul>
<h3 id="heading-boilerplate-code">Boilerplate Code</h3>
<ul>
<li><p><strong>OpenFeign</strong>: You have to define only the endpoint with Interfaces, and the rest is implemented automatically by the framework.</p>
</li>
<li><p><strong>WebClient</strong>: You have a little more code to write and more explicit configuration.</p>
</li>
</ul>
<h3 id="heading-error-handling">Error Handling</h3>
<ul>
<li><p><strong>OpenFeign</strong>: You require custom error handling or fallbacks by <a target="_blank" href="https://stackoverflow.com/questions/39349591/what-is-hystrix-in-spring">Hystrix</a> or <a target="_blank" href="https://codingstrain.com/how-to-implement-circuit-breaker-pattern-with-spring-cloud/">Resilience4j</a>.</p>
</li>
<li><p><strong>WebClient</strong>: Error handling is more flexible with operators like onStatus() and exception mapping.</p>
</li>
</ul>
<h2 id="heading-performance-considerations">Performance Considerations</h2>
<p>When high throughput is not the main concern, OpenFeign is a better choice, since it is well-suited for traditional, blocking applications where simplicity and developer productivity are more important than maximum throughput.</p>
<p>When you have a large number of concurrent requests, such as hundreds or thousands per second, with OpenFeign, you can encounter thread exhaustion problems unless you significantly increase the thread pool sizes. This results in higher memory consumption and increased CPU overhead. For a monolithic application with blocking operations, OpenFeign is better, because mixing blocking and non-blocking models is discouraged.</p>
<p>WebClient is more suitable if your application is I/O bound and has to handle heavy loads. Its non-blocking, reactive nature is excellent for those scenarios, because it can handle more concurrent requests with fewer threads. WebClient does not block a thread while waiting for a response, it releases it immediately to be reused for other work. It also provides a reactive feature called backpressure, used to control the data flow rate. This is useful when dealing with large data streams or when the speed at which clients consume data is too low. It's suited for applications that need to manage thousands of concurrent requests. It is more complex, though, and has a steeper learning curve.</p>
<h2 id="heading-use-cases">Use Cases</h2>
<p><strong>Use OpenFeign When:</strong></p>
<ul>
<li><p>You need to call other services in a Spring Cloud microservice architecture, with tight integration with Service Discovery and Spring Cloud LoadBalancer.</p>
</li>
<li><p>You prefer productivity and simplicity.</p>
</li>
<li><p>You’re bound to a synchronous, blocking model.</p>
</li>
</ul>
<p><strong>Use WebClient When:</strong></p>
<ul>
<li><p>You're using Spring WebFlux to develop the application.</p>
</li>
<li><p>You need full control over request/response handling.</p>
</li>
<li><p>You require high-performance, non-blocking communication.</p>
</li>
<li><p>You want more control over error handling and retry logic.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The architecture and performance requirements of your system guide the choice between OpenFeign and WebClient.</p>
<p>OpenFeign is ideal for synchronous REST calls in a Spring Cloud stack and helps in reducing boilerplate code. WebClient, on the other hand, gives its best for reactive and high-performance applications and is more flexible.</p>
<p>If you're building a traditional microservices system using Spring Boot and Spring Cloud, OpenFeign is most likely to be the obvious choice. If you're in the context of reactive programming or you have to handle thousands of concurrent connections, then WebClient would be a better choice.</p>
<p>Understanding both tools, their pros and cons, is important to make the proper choice.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Benefits of Going RESTful – What is REST and Why You Should Learn About It ]]>
                </title>
                <description>
                    <![CDATA[ By Yiğit Kemal Erinç In this article, we will take a look at Representational State Transfer (REST) principles to learn what they are and what benefits you can get from applying them. I believe it is important to understand why you're learning someth... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/benefits-of-rest/</link>
                <guid isPermaLink="false">66d45e3d73634435aafcef6c</guid>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 31 Dec 2020 23:10:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/12/1_sPLooWMag11pjZnzYXIQCA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yiğit Kemal Erinç</p>
<p>In this article, we will take a look at Representational State Transfer (REST) principles to learn what they are and what benefits you can get from applying them.</p>
<p>I believe it is important to understand why you're learning something – including REST. So let's look at what REST principles bring to the table.</p>
<h2 id="heading-what-is-rest">What is REST?</h2>
<p>Representational State Transfer (REST) is an architectural style that has gained a lot of popularity in recent years due to its simplicity and scalability. </p>
<p>Before REST gained popularity, SOAP was the de-facto way of accessing resources and communicating over the web.</p>
<h2 id="heading-why-should-you-care-about-rest">Why should you care about REST?</h2>
<p>In this section, I'll discuss why REST principles are important and why it's worth the effort to learn more about them. You'll also learn how to apply them to your backend projects.</p>
<h3 id="heading-1-rest-is-easy-to-understand-and-implement">1) REST is Easy to Understand and Implement</h3>
<p>REST is meant to work over HTTP (actually HTTP was influenced by REST). Therefore it makes use of HTTP verbs that most of us know, such as GET, POST, and PUT. </p>
<p>Even if you do not know what these verbs are about, their names are pretty self-explanatory. Also, the clear separation of client and server code makes it easy for different teams to work on different parts (front end or back end) of applications.</p>
<p>Since it's easy to understand and also to implement, REST principles can help increase your dev team's productivity. They are also important if you are going to release a public API for people to develop applications with. </p>
<p>Many people know about REST and HTTP so it will be much easier for them to understand and use your API.</p>
<p><img src="https://ucarecdn.com/f9a4640d-ba7f-4f85-82eb-901a56362a9a/" alt="How to Keep Your Developer Team Happy: Lead Dev New York 2019 | Arc Blog" width="1370" height="765" loading="lazy">
<em>Happy Developers</em></p>
<h3 id="heading-2-rest-makes-your-application-more-scalable">2) REST Makes your Application More Scalable</h3>
<p>There are 2 main reasons why REST can help make your application more scalable:</p>
<h4 id="heading-no-state">No State</h4>
<p>As we will see in the next section (Principles of REST), one of the core principles of REST is that it's stateless on the server-side. Therefore each request will be processed independently from the previous ones.</p>
<p>In applications with a server-side state or sessions, a session is stored for possibly every logged-in user. This session data can easily get bloated and start to occupy a lot of resources on the server. </p>
<p>On the other hand, stateless servers only keep resources (memory) occupied when they are handling a request and they free it as soon as the request is processed.</p>
<p>Since the current trend in scalability is horizontal scaling (typically on the cloud), storing server-side sessions can also make it hard to scale your application because it creates some difficult problems. </p>
<p>For example, say that you have many servers that operate behind a load balancer. What will happen if the client gets to server1 in their first request (server1 now has the client's session) and, at a later time, due to the load on server1, the client gets to server2 which does not know about their previous session data which was stored on server1? Of course, this problem has solutions but it makes scalability more difficult.</p>
<h4 id="heading-faster-data-interchange-format">Faster Data Interchange Format</h4>
<p>RESTful APIs typically use JSON as the data interchange format. JSON is much more compact and smaller in size compared to XML. It can also be parsed faster than XML. (<a target="_blank" href="http://ijcsn.org/IJCSN-2014/3-4/JSON-vs-XML-A-Comparative-Performance-Analysis-of-Data-Exchange-Formats.pdf">source</a>)</p>
<p>While they mostly operate with JSON, also keep in mind that REST APIs are still able to respond with different formats by making use of the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept">Accept header.</a></p>
<h3 id="heading-3-caching-is-easier-with-rest">3) Caching is Easier with REST</h3>
<p>Caching is a critical factor for the scalability and performance of a modern web application. A well-established cache mechanism (with the best hit-rates possible) can drastically decrease the average response time of your server.</p>
<p>REST aims to make caching easier. Since the server is stateless and each request can be processed individually, GET requests should usually return the same response regardless of previous ones and the session.</p>
<p>This makes the GET requests easily cacheable and browsers usually treat them as such. We can also make our POST requests cacheable using <strong>Cache-Control</strong> and <strong>Expires</strong> headers.</p>
<h3 id="heading-4-rest-is-flexibile">4) REST is Flexibile</h3>
<p>By flexibility, I mean that it's easy to modify and it's also able to answer many clients who can ask for different data types (XML, JSON, and so on). </p>
<p>The client can specify the type using the <strong>Accept</strong> header (as I mentioned earlier) and the REST API can return different responses depending on that.</p>
<p>Another mechanism that's worth mentioning is <a target="_blank" href="https://www.wikiwand.com/en/HATEOAS#:~:text=Hypermedia%20as%20the%20Engine%20of,provide%20information%20dynamically%20through%20hypermedia.">HATEOAS</a>. If you do not know the term, don't worry, it basically means: Return the related URLs in the server response for a particular resource. </p>
<p>Take a look at this example from Wikipedia. The client requests account information with <code>account_number</code> from a bank API and gets this response:</p>
<pre><code>
{
    <span class="hljs-string">"account"</span>: {
        <span class="hljs-string">"account_number"</span>: <span class="hljs-number">12345</span>,
        <span class="hljs-string">"balance"</span>: {
            <span class="hljs-string">"currency"</span>: <span class="hljs-string">"usd"</span>,
            <span class="hljs-string">"value"</span>: <span class="hljs-number">100.00</span>
        },
        <span class="hljs-string">"links"</span>: {
            <span class="hljs-string">"deposit"</span>: <span class="hljs-string">"/accounts/12345/deposit"</span>,
            <span class="hljs-string">"withdraw"</span>: <span class="hljs-string">"/accounts/12345/withdraw"</span>,
            <span class="hljs-string">"transfer"</span>: <span class="hljs-string">"/accounts/12345/transfer"</span>,
            <span class="hljs-string">"close"</span>: <span class="hljs-string">"/accounts/12345/close"</span>
        }
    }
}
</code></pre><p>This server makes use of HATEOAS and returns the links for corresponding actions. This makes it very easy to explore the API and also makes it flexible by allowing the server to change the endpoints.</p>
<p>Think of it like this: if the server weren't applying HATEOAS, the client would need to hardcode the endpoints such as "/accounts/:account-id/deposit". But if the server changes the URL to "/accounts/:account-id/depositMoney", the client code also needs to be changed. </p>
<p>With the help of HATEOAS links, the client can check the link by parsing this JSON and easily make the request. If the endpoint changes, they will be provided with the new one, without the need to change the client code.</p>
<p>For more insights on this topic, you can check out <a target="_blank" href="https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">this</a> blog post from Roy Fielding himself.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article I have tried to express why I value REST and why I believe you should value it as well. I hope that after reading this, the reasons to apply REST standards are now more clear to you.</p>
<p>This article can serve as a motivation to learn more about the topic. And I have some good news: I am planning to write about REST Best Practices and common mistakes in the near future. </p>
<p>If you are interested you can keep an eye on or subscribe to my <a target="_blank" href="http://erinc.io/">blog</a>. You can also take a look at my previous posts there :)</p>
<p>If you have any questions or want to discuss the topic further, you can feel free to contact me.</p>
<p>Have a Happy New Year and thank you for reading. :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn How to Deploy a Full Stack Web App with Heroku ]]>
                </title>
                <description>
                    <![CDATA[ By M. S. Farzan Building a full stack web app is no mean feat. Learning to deploy one to production so that you can share it with the world can add an additional layer of complexity. In this new tutorial, we'll learn how to deploy a full stack MEVN a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-deploy-a-full-stack-web-app-with-heroku/</link>
                <guid isPermaLink="false">66d851ef8acc348be2a441c2</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ deployment ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ full stack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Heroku ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MongoDB ]]>
                    </category>
                
                    <category>
                        <![CDATA[ mongoose ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ vue ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 22 Jun 2020 01:32:32 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9a22740569d1a4ca23bc.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By M. S. Farzan</p>
<p>Building a full stack web app is no mean feat. Learning to deploy one to production so that you can share it with the world can add an additional layer of complexity.</p>
<p>In this new tutorial, we'll learn how to deploy a <a target="_blank" href="https://www.freecodecamp.org/news/build-a-full-stack-mevn-app/">full stack MEVN app</a> to Heroku!</p>
<p>Follow along (46 minute watch):</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/rUSjVri4I30" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>You can follow the original tutorial to build this app <a target="_blank" href="https://www.freecodecamp.org/news/build-a-full-stack-mevn-app/">here</a>.</p>
<p>Happy coding!</p>
<p>If you enjoyed this article, please consider <a target="_blank" href="https://www.nightpathpub.com/">checking out my games and books</a>, <a target="_blank" href="https://www.youtube.com/msfarzan?sub_confirmation=1">subscribing to my YouTube channel</a>, or <a target="_blank" href="https://discord.gg/RF6k3nB">joining the <em>Entromancy</em> Discord</a>.</p>
<p>M. S. Farzan, Ph.D. has written and worked for high-profile video game companies and editorial websites such as Electronic Arts, Perfect World Entertainment, Modus Games, and MMORPG.com, and has served as the Community Manager for games like <em>Dungeons &amp; Dragons Neverwinter</em> and <em>Mass Effect: Andromeda</em>. He is the Creative Director and Lead Game Designer of <em><a target="_blank" href="https://www.nightpathpub.com/rpg">Entromancy: A Cyberpunk Fantasy RPG</a></em> and author of <em><a target="_blank" href="http://nightpathpub.com/books">The Nightpath Trilogy</a></em>. Find M. S. Farzan on Twitter <a target="_blank" href="https://twitter.com/sominator">@sominator</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ REST API Tutorial – REST Client, REST Service, and API Calls Explained With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Vaibhav Kandwal Ever wondered how login/signup on a website works on the back-end? Or how when you search for "cute kitties" on YouTube, you get a bunch of results and are able to stream off of a remote machine? In this beginner friendly guide, I ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rest-api-tutorial-rest-client-rest-service-and-api-calls-explained-with-code-examples/</link>
                <guid isPermaLink="false">66d45dd78812486a37369c6d</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express JS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 22 Apr 2020 19:05:27 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9b84740569d1a4ca2c3f.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Vaibhav Kandwal</p>
<p>Ever wondered how login/signup on a website works on the back-end? Or how when you search for "cute kitties" on YouTube, you get a bunch of results and are able to stream off of a remote machine?</p>
<p>In this beginner friendly guide, I will walk you through the process of setting up a RESTful API. We'll declassify some of the jargon and have a look at how we can code a server in NodeJS. Let's dive a bit deeper into JavaScript!</p>
<h2 id="heading-get-that-jargon-away">Get that jargon away</h2>
<p>So, what is REST? According to Wikipedia:</p>
<blockquote>
<p><strong>Representational state transfer</strong> (<strong>REST</strong>) is a software architectural style that defines a set of constraints to be used for creating Web services. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations</p>
</blockquote>
<p>Let's demystify what that means (hopefully you got the full form). REST is basically a set of rules for communication between a client and server. There are a few constraints on the definition of REST:</p>
<ol>
<li><strong>Client-Server Architecture</strong>: the user interface of the website/app should be separated from the data request/storage, so each part can be scaled individually.</li>
<li><strong>Statelessness</strong>: the communication should have no client context stored on server. This means each request to the server should be made with all the required data and no assumptions should be made if the server has any data from previous requests.</li>
<li><strong>Layered system</strong>: client should not be able to tell if it is communicating directly with the server or some intermediary. These intermediary servers (be it proxy or load balancers) allow for scalability and security of the underlying server.</li>
</ol>
<p>Okay, so now that you know what RESTful services are, here are some of the terms used in the heading:</p>
<ol>
<li><strong>REST Client</strong>: code or an app that can access these REST services. You are using one right now! Yes, the browser can act as an uncontrolled REST client (the website handles the browser requests). The browser, for a long time, used an in-built function called XMLHttpRequest for all REST requests. But, this was succeeded by <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">FetchAPI</a>, a modern, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a> based approach to requests. Others examples are code libraries like <a target="_blank" href="https://github.com/axios/axios">axios</a>, <a target="_blank" href="https://github.com/visionmedia/superagent">superagent</a> and <a target="_blank" href="https://github.com/sindresorhus/got">got</a> or some dedicated apps like <a target="_blank" href="https://www.postman.com/">Postman</a> (or an online version, <a target="_blank" href="https://postwoman.io/">postwoman</a>!), or a command line tool like <a target="_blank" href="https://curl.haxx.se/">cURL</a>!.</li>
<li><strong>REST Service</strong>: the server. There are many popular libraries that make creation of these servers a breeze, like <a target="_blank" href="https://expressjs.com/">ExpressJS</a> for NodeJS and <a target="_blank" href="https://www.djangoproject.com/">Django</a> for Python.</li>
<li><strong>REST API</strong>: this defines the endpoint and methods allowed to access/submit data to the server. We will talk about this in great detail below. Other alternatives to this are: GraphQL, JSON-Pure and oData.</li>
</ol>
<h2 id="heading-so-tell-me-now-how-does-rest-look">So tell me now, how does REST look?</h2>
<p>In very broad terms, you ask the server for a certain data or ask it to save some data, and the server responds to the requests.</p>
<p>In programming terms, there is an endpoint (a URL) that the server is waiting to get a request. We connect to that endpoint and send in some data about us (remember, REST is stateless, no data about the request is stored) and the server responds with the correct response.</p>
<p>Words are boring, let me give you a demonstration. I will be using Postman to show you the request and response:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-162.png" alt="Image" width="600" height="400" loading="lazy">
<em>postman: setting up request</em></p>
<p>The returned data is in JSON (JavaScript Object Notation) and can be accessed directly.</p>
<p>Here, <code>https://official-joke-api.appspot.com/random_joke</code> is called an endpoint of an API. There will be a server listening on that endpoint for requests like the one we made.</p>
<h2 id="heading-anatomy-of-rest">Anatomy of REST:</h2>
<p>Alright, so now we know that data can be requested by the client and the server will respond appropriately. Let's look deeper into how a request is formed.</p>
<ol>
<li><strong>Endpoint</strong>: I have already told you about this. For a refresher, it is the URL where the REST Server is listening.</li>
<li><strong>Method</strong>: Earlier, I wrote that you can either request data or modify it, but how will the server know what kind of operation the client wants to perform? REST implements multiple 'methods' for different types of request, the following are most popular:  </li>
<li><strong>GET</strong>: Get resource from the server.  </li>
<li><strong>POST</strong>: Create resource to the server.  </li>
<li><strong>PATCH</strong> or <strong>PUT</strong>: Update existing resource on the server.  </li>
<li><p><strong>DELETE</strong>: Delete existing resource from the server.  </p>
</li>
<li><p><strong>Headers</strong>: The additional details provided for communication between client and server (remember, REST is stateless). Some of the common headers are:<br><strong>Request:</strong>  </p>
</li>
<li><em>host</em>: the IP of client (or from where request originated)  </li>
<li><em>accept-language</em>: language understandable by the client  </li>
<li><em>user-agent</em>: data about client, operating system and vendor<br><strong>Response</strong>:  </li>
<li><em>status</em>: the status of request or HTTP code.  </li>
<li><em>content-type</em>: type of resource sent by server.  </li>
<li><em>set-cookie</em>: sets cookies by server</li>
<li><strong>Data</strong>: (also called body or message) contains info you want to send to the server.</li>
</ol>
<h2 id="heading-enough-with-the-details-show-me-the-code">Enough with the details – show me the code.</h2>
<p>Let's begin coding a REST Service in Node. We will be implementing all the things we learnt above. We will also be using ES6+ to write our service in.</p>
<p>Make sure you have Node.JS installed and <code>node</code> and <code>npm</code> are available in your path. I will be using Node 12.16.2 and NPM 6.14.4.</p>
<p>Create a directory <code>rest-service-node</code> and cd into it:</p>
<pre><code class="lang-shell">mkdir rest-service-node
cd rest-service-node
</code></pre>
<p>Initialize the node project:</p>
<pre><code class="lang-shell">npm init -y
</code></pre>
<p>The <code>-y</code> flag skips all the questions. If you want to fill in the whole questionnaire, just run <code>npm init</code>.</p>
<p> Let's install some packages. We will be using the ExpressJS framework for developing the REST Server. Run the following command to install it:</p>
<pre><code class="lang-shell">npm install --save express body-parser
</code></pre>
<p>What's <code>body-parser</code> there for? Express, by default, is incapable of handling data sent via POST request as JSON. <code>body-parser</code> allows Express to overcome this.</p>
<p>Create a file called <code>server.js</code> and add the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">"body-parser"</span>);

<span class="hljs-keyword">const</span> app = express();

app.use(bodyParser.json());

app.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port 5000.`</span>);
});
</code></pre>
<p>The first two lines are importing Express and body-parser. </p>
<p>Third line initializes the Express server and sets it to a variable called <code>app</code>. </p>
<p>The line, <code>app.use(bodyParser.json());</code> initializes the body-parser plugin.</p>
<p>Finally, we are setting our server to listen on port <code>5000</code> for requests.</p>
<h3 id="heading-getting-data-from-the-rest-server">Getting data from the REST Server:</h3>
<p>To get data from a server, we need a <code>GET</code> request. Add the following code before <code>app.listen</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sayHi = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">"Hi!"</span>);
};

app.get(<span class="hljs-string">"/"</span>, sayHi);
</code></pre>
<p> We have created a function <code>sayHi</code> which takes two parameters <code>req</code> and <code>res</code> (I will explain later) and sends a 'Hi!' as response. </p>
<p><code>app.get()</code> takes two parameters, the route path and function to call when the path is requested by the client. So, the last line translates to: Hey server, listen for requests on the '/' (think homepage) and call the <code>sayHi</code> function if a request is made.</p>
<p><code>app.get</code> also gives us a <code>request</code> object containing all the data sent by the client and a <code>response</code> object which contains all the methods with which we can respond to the client. Though these are accessible as function parameters, the general naming convention suggests we name them <code>res</code> for <code>response</code> and <code>req</code> for <code>request</code>.</p>
<p>Enough chatter. Let's fire up the server! Run the following server:</p>
<pre><code class="lang-shell">node server.js
</code></pre>
<p>If everything is successful, you should see a message on console saying: <em>Server is running on port 5000.</em></p>
<p><em>Note: You can change the port to whatever number you want.</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-160.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Open up your browser and navigate to <code>http://localhost:5000/</code> and you should see something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-161.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>There you go! Your first <code>GET</code> request was successful!</p>
<h3 id="heading-sending-data-to-rest-server">Sending data to REST Server:</h3>
<p>As we have discussed earlier, let's setup how we can implement a <code>POST</code> request into our server. We will be sending in two numbers and the server will return the sum of the numbers. Add this new method below the <code>app.get</code> :</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">"/add"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { a, b } = req.body;
  res.send(<span class="hljs-string">`The sum is: <span class="hljs-subst">${a + b}</span>`</span>);
});
</code></pre>
<p>Here, we will be sending the data in JSON format, like this:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"a"</span>:<span class="hljs-number">5</span>,
    <span class="hljs-attr">"b"</span>:<span class="hljs-number">10</span>
}
</code></pre>
<p>Let's get over the code:</p>
<p>On line 1, we are invoking the .<code>post()</code> method of ExpressJS, which allows the server to listen for <code>POST</code> requests. This function takes in the same parameters as the <code>.get()</code> method. The route that we are passing is <code>/add</code>, so one can access the endpoint as <code>http://your-ip-address:port/add</code> or in our case <code>localhost:5000/add</code>. We are inlining our function instead of writing a function elsewhere. </p>
<p>On line 2, we have used a bit of ES6 syntax, namely, object destructuring. Whatever data we send via the request gets stored and is available in the <code>body</code> of the <code>req</code> object. So essentially, we could've replaced line 2 with something like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num1 = req.body.a;
<span class="hljs-keyword">const</span> num2 = req.body.b;
</code></pre>
<p>On line 3, we are using the <code>send()</code> function of the <code>res</code> object to send the result of the sum. Again, we are using template literals from ES6. Now to test it (using Postman):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-163.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So we have sent the data 5 and 10 as <code>a</code> and <code>b</code> using them as the body. Postman attaches this data to the request and sends it. When the server receives the request, it can parse the data from <code>req.body</code> , as we did in the code above. The result is shown below.</p>
<p>Alright, the final code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">"body-parser"</span>);

<span class="hljs-keyword">const</span> app = express();

app.use(bodyParser.json());

<span class="hljs-keyword">const</span> sayHi = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">"Hi!"</span>);
};

app.get(<span class="hljs-string">"/"</span>, sayHi);

app.post(<span class="hljs-string">"/add"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { a, b } = req.body;
  res.send(<span class="hljs-string">`The sum is: <span class="hljs-subst">${a + b}</span>`</span>);
});

app.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port 5000.`</span>);
});
</code></pre>
<h2 id="heading-rest-client">REST Client:</h2>
<p>Okay, we have created a server, but how do we access it from our website or webapp? Here the REST client libraries will come in handy. </p>
<p>We will be building a webpage which will contain a form, where you can enter two numbers and we will display the result. Let's start.</p>
<p>First, let's change the <code>server.js</code> a bit:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">"body-parser"</span>);

<span class="hljs-keyword">const</span> app = express();

app.use(bodyParser.json());

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.sendFile(path.join(__dirname, <span class="hljs-string">"index.html"</span>));
});

app.post(<span class="hljs-string">"/add"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { a, b } = req.body;
  res.send({
    <span class="hljs-attr">result</span>: <span class="hljs-built_in">parseInt</span>(a) + <span class="hljs-built_in">parseInt</span>(b)
  });
});

app.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port 5000.`</span>);
});
</code></pre>
<p>We imported a new package <code>path</code>, which is provided by Node, to manipulate path cross-platform. Next we changed the <code>GET</code> request on '/' and use another function available in <code>res</code>, ie. <code>sendFile</code>, which allows us to send any type of file as response. So, whenever a person tries to navigate to '/', they will get our <code>index.html</code> page.</p>
<p>Finally, we changed our <code>app.post</code> function to return the sum as JSON and convert both <code>a</code> and <code>b</code> to integers.</p>
<p>Let's create an html page, I will call it <code>index.html</code>, with some basic styling:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>REST Client<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
    * {
      <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
      <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
      <span class="hljs-attribute">box-sizing</span>: border-box;
    }
    <span class="hljs-selector-class">.container</span> {
      <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
      <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Helvetica, Arial, sans-serif, <span class="hljs-string">"Apple Color Emoji"</span>, <span class="hljs-string">"Segoe UI Emoji"</span>, <span class="hljs-string">"Segoe UI Symbol"</span>;
      <span class="hljs-attribute">display</span>: flex;
      <span class="hljs-attribute">flex-direction</span>: column;
      <span class="hljs-attribute">justify-content</span>: center;
      <span class="hljs-attribute">align-items</span>: center;
    }
    <span class="hljs-selector-tag">form</span> {
      <span class="hljs-attribute">display</span>: flex;
      <span class="hljs-attribute">flex-direction</span>: column;
      <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
    }
    <span class="hljs-selector-tag">label</span>,
    <span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=<span class="hljs-string">"submit"</span>]</span> {
      <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Simple POST Form<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Number 1:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"num1"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Number 2:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"num2"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Add"</span>/&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"result"</span>&gt;</span>Click Add!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Let's add a <code>script</code> tag just before the closing body tag, so we don't need to maintain a <code>.js</code> file. We will begin by listening for the <code>submit</code> event and call a function accordingly:</p>
<pre><code class="lang-js">&lt;script&gt;
    <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">"submit"</span>, sendData);
&lt;/script&gt;
</code></pre>
<p>First we need to prevent page refresh when the 'Add' button is clicked. This can be done using the <code>preventDefault()</code> function. Then, we will get the value of the inputs at that instant:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendData</span>(<span class="hljs-params">e</span>) </span>{
    e.preventDefault();
    <span class="hljs-keyword">const</span> a = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#num1"</span>).value;
    <span class="hljs-keyword">const</span> b = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#num2"</span>).value;
}
</code></pre>
<p>Now we will make the call to the server with both these values <code>a</code> and <code>b</code>. We will be using the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a>, built-in to every browser for this. </p>
<p>Fetch takes in two inputs, the URL endpoint and a JSON request object and returns a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>. Explaining them here will be out-of-bounds here, so I'll leave that for you.</p>
<p>Continue inside the <code>sendData()</code> function:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">"/add"</span>, {
        <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-attr">Accept</span>: <span class="hljs-string">"application/json"</span>,
            <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>
        },
        <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
            <span class="hljs-attr">a</span>: <span class="hljs-built_in">parseInt</span>(a),
            <span class="hljs-attr">b</span>: <span class="hljs-built_in">parseInt</span>(b)
        })
    })
    .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-keyword">const</span> {
            result
        } = data;
        <span class="hljs-built_in">document</span>.querySelector(
            <span class="hljs-string">".result"</span>
        ).innerText = <span class="hljs-string">`The sum is: <span class="hljs-subst">${result}</span>`</span>;
    })
    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(err));
</code></pre>
<p>First we are passing the relative URL of the endpoint as the first parameter to <code>fetch</code>. Next, we are passing an object which contains the method we want Fetch to use for the request, which is <code>POST</code> in this case.</p>
<p>We are also passing <code>headers</code>, which will provide information about the type of data we are sending (<code>content-type</code>) and the type of data we accept as response (<code>accept</code>).</p>
<p>Next we pass <code>body</code>. Remember we typed the data as JSON while using Postman? We're doing kind of a similar thing here. Since express deals with string as input and processes it according to content-type provided, we need to convert our JSON payload into string. We do that with <code>JSON.stringify()</code>. We're being a little extra cautious and parsing the input into integers, so it doesn't mess up our server (since we haven't implemented any data-type checking).</p>
<p>Finally, if the promise (returned by fetch) resolves, we will get that response and convert it into JSON. After that, we will get the result from the <code>data</code> key returned by the response. Then we are simply displaying the result on the screen.</p>
<p>At the end, if the promise is rejected, we will display the error message on the console.</p>
<p>Here's the final code for <code>index.html</code>:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>REST Client<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
    * {
      <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
      <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
      <span class="hljs-attribute">box-sizing</span>: border-box;
    }
    <span class="hljs-selector-class">.container</span> {
      <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
      <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Helvetica, Arial, sans-serif, <span class="hljs-string">"Apple Color Emoji"</span>, <span class="hljs-string">"Segoe UI Emoji"</span>, <span class="hljs-string">"Segoe UI Symbol"</span>;
      <span class="hljs-attribute">display</span>: flex;
      <span class="hljs-attribute">flex-direction</span>: column;
      <span class="hljs-attribute">justify-content</span>: center;
      <span class="hljs-attribute">align-items</span>: center;
    }
    <span class="hljs-selector-tag">form</span> {
      <span class="hljs-attribute">display</span>: flex;
      <span class="hljs-attribute">flex-direction</span>: column;
      <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
    }
    <span class="hljs-selector-tag">label</span>,
    <span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=<span class="hljs-string">"submit"</span>]</span> {
      <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Simple POST Form<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Number 1:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"num1"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Number 2:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"num2"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Add"</span>/&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"result"</span>&gt;</span>Click Add!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">"submit"</span>, sendData);
      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendData</span>(<span class="hljs-params">e</span>) </span>{
        e.preventDefault();
        <span class="hljs-keyword">const</span> a = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#num1"</span>).value;
        <span class="hljs-keyword">const</span> b = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#num2"</span>).value;

        fetch(<span class="hljs-string">"/add"</span>, {
          <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
          <span class="hljs-attr">headers</span>: {
            <span class="hljs-attr">Accept</span>: <span class="hljs-string">"application/json"</span>,
            <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>
          },
          <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
            <span class="hljs-attr">a</span>: <span class="hljs-built_in">parseInt</span>(a),
            <span class="hljs-attr">b</span>: <span class="hljs-built_in">parseInt</span>(b)
          })
        })
          .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
          .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
            <span class="hljs-keyword">const</span> { result } = data;
            <span class="hljs-built_in">document</span>.querySelector(
              <span class="hljs-string">".result"</span>
            ).innerText = <span class="hljs-string">`The sum is: <span class="hljs-subst">${result}</span>`</span>;
          })
          .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(err));
      }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>I have spun up a <a target="_blank" href="https://habitual-serious-boater.glitch.me/">little app on glitch</a> for you to test.</p>
<h2 id="heading-conclusion">Conclusion:</h2>
<p>So in this post, we learnt about REST architecture and the anatomy of REST requests. We worked our way through by creating a simple REST Server that serves <code>GET</code> and <code>POST</code> requests and built a simple webpage that uses a REST Client to display the sum of two numbers. </p>
<p>You can extend this for the remaining types of requests and even implement a full featured <a target="_blank" href="https://www.freecodecamp.org/news/building-a-simple-crud-application-with-express-and-mongodb-63f80f3eb1cd/">back-end CRUD app</a>. </p>
<p>I hope you have learned something from this. If you have any questions, feel free to reach out to me over twitter! Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Three Things to Consider Before Deploying Your First Full Stack App ]]>
                </title>
                <description>
                    <![CDATA[ By M. S. Farzan Building a full stack app is no small endeavor, and deploying it comes with its own host of things to consider. I'm a tabletop game developer, and recently deployed a simple roleplaying game tracker that uses the M-E-V-N stack (you ca... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/3-things-to-consider-before-deploying-your-first-full-stack-app/</link>
                <guid isPermaLink="false">66d851dd836d1162d8815c3c</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Azure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ containers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ deployment ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ full stack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Heroku ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Kubernetes ]]>
                    </category>
                
                    <category>
                        <![CDATA[ mongoose ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ vue ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 17 Mar 2020 21:12:22 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9c1d740569d1a4ca3007.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By M. S. Farzan</p>
<p>Building a full stack app is no small endeavor, and deploying it comes with its own host of things to consider.</p>
<p>I'm a <a target="_blank" href="https://www.nightpathpub.com/entromancy">tabletop game</a> developer, and recently deployed a simple <a target="_blank" href="https://mevn-rpg-app.herokuapp.com/">roleplaying game tracker</a> that uses the <a target="_blank" href="https://www.mongodb.com/">M</a>-<a target="_blank" href="https://expressjs.com/">E</a>-<a target="_blank" href="https://vuejs.org/">V</a>-<a target="_blank" href="https://nodejs.org/en/">N</a> stack (you can follow my tutorial to create your own app <a target="_blank" href="https://www.freecodecamp.org/news/build-a-full-stack-mevn-app/">here</a>).  </p>
<p>In deploying the app, I came across three key takeaways that may be useful as you begin considering the best way to bring your projects from development to production. </p>
<p>You can check out the code to my app on <a target="_blank" href="https://github.com/sominator/mevn-rpg-app">GitHub</a>, and I should mention that it includes Chad Carteret's <a target="_blank" href="https://codepen.io/retractedhack/pen/gPLpWe">very cool CSS statblock</a> in prettifying what's otherwise very basic HTML.</p>
<p>If you're thinking of following the same path to deployment as I have here, be sure to check out the official documentation on <a target="_blank" href="https://devcenter.heroku.com/articles/deploying-nodejs">Heroku</a>, the <a target="_blank" href="https://cli.vuejs.org/guide/deployment.html">Vue CLI</a>, and <a target="_blank" href="https://medium.com/netscape/deploying-a-vue-js-2-x-app-to-heroku-in-5-steps-tutorial-a69845ace489">this tutorial</a> by Nick Manning.</p>
<p>You'll also want to take a look at Will Abramson's <a target="_blank" href="https://www.freecodecamp.org/news/lessons-learned-from-deploying-my-first-full-stack-web-application-34f94ec0a286/">article on a similar topic</a>.</p>
<p>On to deployment!</p>
<h2 id="heading-your-front-end-and-back-end-can-be-deployed-together-or-separately-depending-on-your-apps-complexity">Your front end and back end can be deployed together or separately, depending on your app's complexity.</h2>
<p>One snag that seems to appear immediately when considering production is the structural question of how to deploy the front and back ends of your app.</p>
<p>Should the client (or static files) live in the same place as the server and database? Or should they be separate, with the front end making HTTP requests from elsewhere to the back end using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a>?</p>
<p>The answer is yes! Or no. Maybe??</p>
<p>For better or worse, there's no one-size-fits-all solution to this question, as it will likely depend on your app's architecture and complexity. In the roleplaying game tracker that I linked to above, I have the whole stack running on a single Heroku <a target="_blank" href="https://www.heroku.com/dynos">dyno</a>, with the following folder structure:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Folder-Structure.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>All of the front and back end files live in the same place, with the Vue client built for production in a folder located at /client/dist.</p>
<p>In server.js, along with a bunch of database and routing code, there's a little line that says:</p>
<pre><code class="lang-javascript">server.use(serveStatic(__dirname + <span class="hljs-string">"/client/dist"</span>));
</code></pre>
<p>In Express, this tells the app to serve my static client files from a particular folder, and enables me to run the front and back ends all within the same environment. If you're deploying a similarly simple app, this type of solution might work for you as well.  </p>
<p>Conversely, and depending on your project's complexity, you may have to separate the front and back ends and treat them as separate applications, which is no big deal. In the app above, my client is making calls to static API endpoints that are handled by the server, like this:</p>
<pre><code class="lang-javascript">getQuests: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    axios
        .get(<span class="hljs-string">'https://mevn-rpg-app.herokuapp.com/quests'</span>)
        .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> (<span class="hljs-built_in">this</span>.questData = response.data))                   
 }
</code></pre>
<p>Technically, my client could be making those requests from anywhere - even a static GitHub Pages site. This type of solution can help separate your app into two distinct entities to tackle, which is sometimes better than trying to cram the whole project into one location.</p>
<p>One note: if you're going to be making cross-origin HTTP requests - that is, requests from a client that lives on a separate domain from the API or server - you'll need to become familiar with <a target="_blank" href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">CORS</a>.  You can read more about it in <a target="_blank" href="https://www.freecodecamp.org/news/i-built-a-web-api-with-express-flask-aspnet/">this article</a>.  </p>
<h2 id="heading-your-code-will-need-to-change-to-support-a-production-environment">Your code will need to change to support a production environment.</h2>
<p>When you're knee deep in the development process, it can be easy to lose track of how much of your code depends on local files or other data.</p>
<p>Consider the following in a locally-running server.js:</p>
<pre><code class="lang-javascript">server.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Server started!"</span>));
</code></pre>
<p>On a local machine, the code just asks the server to listen on port 3000 and log to the console that we're ready for liftoff.</p>
<p>In a production environment, the server has no concept of where the "localhost" should be, or to whose port 3000 it should be listening. With this example, you'd have to change your code to something like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;

server.listen(port, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Server started!"</span>));
</code></pre>
<p>The above instructs the server to instead listen at port 3000 of the <em>process</em> that's currently running, wherever that might be (check out <a target="_blank" href="https://codeburst.io/process-env-what-it-is-and-why-when-how-to-use-it-effectively-505d0b2831e7">this article</a> for further reading on this topic).</p>
<p>Similarly, in my app, I have several modules that need to be imported by one another to function:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Folder-Structure-Expanded.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In /routes/Quests.js, for example, I have a router that tells the server what to do when receiving API requests to interact with quest-related items in the database. The router needs to import a <a target="_blank" href="https://mongoosejs.com/docs/guide.html">Mongoose schema</a> from /models/quest.js to function properly. If the application were running locally, we could just say:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> Quest = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../models/quest'</span>);
</code></pre>
<p>Pretty simple! Yet, unfortunately, our server won't know where to find the root directory of our project once deployed. In Express, we'd change our code to something like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);
<span class="hljs-keyword">const</span> Quest = <span class="hljs-built_in">require</span>(path.join(__dirname, <span class="hljs-string">'../models/quest'</span>));
</code></pre>
<p>Your particular case might be different, depending on your language and framework(s), but you'll need to get specific about what your code looks like in a production environment rather than in your local development environment.</p>
<p>Additionally, you're probably already familiar with whatever bundler you're using for your front end (e.g., <a target="_blank" href="https://webpack.js.org/">webpack</a>), and will want to build your client for production to optimize it for deployment.</p>
<h2 id="heading-you-have-a-multitude-of-deployment-platforms-from-which-to-choose">You have a multitude of deployment platforms from which to choose.</h2>
<p>If you've deployed a front end website or some other type of static app, you might be familiar with just pushing your files to some remote repository and calling it a day.</p>
<p>Deploying a full stack app (or even just a back end) is eminently more complex. You'll need a dedicated server, or something that emulates one, to respond to the HTTP requests that it will be receiving and work with an online database.</p>
<p>There are a number of services that will do this very thing for you, and the spectrum ranges based on price, scalability, complexity, and other factors.</p>
<p>There's a bunch of articles out there that compare <a target="_blank" href="https://en.wikipedia.org/wiki/Platform_as_a_service">PaaS</a> options for deployment, but here are some thoughts as you consider platforms for your first project:</p>
<ul>
    <li><strong>Heroku</strong>: If you have a small project like mine or just want to learn about deployment, a good first step could be <a href="https://www.heroku.com/">Heroku</a>.</li>
    <li><strong>AWS, Docker, and Kubernetes</strong>: If you're seeking a career in full stack web development or DevOps, now's a good time to familiarize yourself with <a href="https://aws.amazon.com/">Amazon Web Services</a> and/or container platforms like <a href="https://www.docker.com/">Docker</a> and <a href="https://kubernetes.io/">Kubernetes</a>.</li>
    <li><strong>Azure</strong>: If you're a C# or .NET developer, <a href="https://azure.microsoft.com/en-us/">Azure</a> appears to be a seamless way to deploy your apps without having to leave the safety of the Microsoft ecosystem.</li>
</ul>

<p>There are, of course, several other options out there, and your particular use-case scenario might depend on pricing or the specific feature sets that are on offer.</p>
<p>Additionally, you'll want to consider any addons that will be necessary to replicate your app's functionality in a production environment. My roleplaying game tracker, for example, uses MongoDB, but the production version certainly can't use the little database on my local machine! Instead, I've used the <a target="_blank" href="https://elements.heroku.com/addons/mongolab">mLab</a> Heroku addon to get the live site up and running with the same functionality as in my development environment.</p>
<p>Your app's success, as well as your own progress as a full stack web developer, depend on your ability to consider deployment options and create a successful pipeline for production. With a little research, I'm certain that you can find the best solution that fits all of your app's needs.</p>
<p>Happy coding!</p>
<p>If you enjoyed this article, please consider <a target="_blank" href="https://www.nightpathpub.com/">checking out my games and books</a>, <a target="_blank" href="https://www.youtube.com/msfarzan?sub_confirmation=1">subscribing to my YouTube channel</a>, or <a target="_blank" href="https://discord.gg/RF6k3nB">joining the <em>Entromancy</em> Discord</a>.</p>
<p>M. S. Farzan, Ph.D. has written and worked for high-profile video game companies and editorial websites such as Electronic Arts, Perfect World Entertainment, Modus Games, and MMORPG.com, and has served as the Community Manager for games like <em>Dungeons &amp; Dragons Neverwinter</em> and <em>Mass Effect: Andromeda</em>. He is the Creative Director and Lead Game Designer of <em><a target="_blank" href="https://www.nightpathpub.com/rpg">Entromancy: A Cyberpunk Fantasy RPG</a></em> and author of <em><a target="_blank" href="http://nightpathpub.com/books">The Nightpath Trilogy</a></em>. Find M. S. Farzan on Twitter <a target="_blank" href="https://twitter.com/sominator">@sominator</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Full Stack RPG Character Generator with MongoDB, Express, Vue, and Node (the MEVN Stack) ]]>
                </title>
                <description>
                    <![CDATA[ By M. S. Farzan I'm a tabletop game developer, and enjoy making apps that have the potential to perform some service related to gaming. In this article, we'll walk through the steps to create a roleplaying game character generator using MongoDB, Expr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-a-full-stack-mevn-app/</link>
                <guid isPermaLink="false">66d851dfe0db794d56c01bf3</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ full stack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ mongoose ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ vue ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 09 Mar 2020 18:50:41 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9c3a740569d1a4ca30ca.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By M. S. Farzan</p>
<p>I'm a <a target="_blank" href="https://www.nightpathpub.com/">tabletop game</a> developer, and enjoy making apps that have the potential to perform some service related to gaming. In this article, we'll walk through the steps to create a roleplaying game character generator using <a target="_blank" href="https://www.mongodb.com/">MongoDB</a>, <a target="_blank" href="https://expressjs.com/">Express</a>, <a target="_blank" href="http://vuejs.org/">Vue</a>, and <a target="_blank" href="https://nodejs.org/en/">Node</a> (also known as the "MEVN" stack). </p>
<p>Prerequisites: this tutorial presumes that you have Node/<a target="_blank" href="https://www.npmjs.com/">NPM</a> and MongoDB installed and configured, with a code editor and <a target="_blank" href="https://en.wikipedia.org/wiki/Command-line_interface">CLI</a> (or <a target="_blank" href="https://www.freecodecamp.org/news/how-to-set-up-an-integrated-development-environment-ide/">IDE</a>) ready to go.</p>
<p>If you'd prefer to follow along with a visual tutorial, you can check out the companion video to this article below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/i5XUgda08qk" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>I should also mention that this tutorial would not have been possible without Bennett Dungan's article on <a target="_blank" href="https://dev.to/beznet/build-a-rest-api-with-node-express-mongodb-4ho4">building a REST API</a>, Aneeta Sharma's tutorial on <a target="_blank" href="https://medium.com/@anaida07/mevn-stack-application-part-1-3a27b61dcae0">full stack MEVN web apps</a>, and Matt Maribojoc's article on <a target="_blank" href="https://medium.com/@mattmaribojoc/creating-a-todo-app-with-a-mevn-full-stack-part-1-da0f4df7e15">the same topic</a>.  </p>
<p>I used each of these articles in addition to official documentation (for <a target="_blank" href="https://vuejs.org/v2/guide/">Vue</a>, <a target="_blank" href="https://expressjs.com/en/starter/installing.html">Express</a>, and a whole lot more) in learning to create my own MEVN apps (you can read more about my journey with web APIs <a target="_blank" href="https://www.freecodecamp.org/news/i-built-a-web-api-with-express-flask-aspnet/">here</a>). </p>
<p>You can access the entire repository for this tutorial on <a target="_blank" href="https://github.com/sominator/mevn-character-generator">GitHub</a>.</p>
<h2 id="heading-the-front-end">The Front End</h2>
<p>Our app is going to allow us to create new roleplaying game characters and view them altogether, with the following stack:</p>
<ul>
    <li>Vue Client</li>
    <li>Node/Express Server</li>
    <li>MongoDB Database</li>
</ul>

<p>The Vue Client will make <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">HTTP requests</a> to the Node/Express Server (or "<a target="_blank" href="https://en.wikipedia.org/wiki/Application_programming_interface">API</a>"), which will in turn communicate with our MongoDB Database to send data back up the stack.</p>
<p>We'll begin by opening a command line, creating a new directory for our project, and navigating into that directory:</p>
<pre><code class="lang-cli">mkdir mevn-character-generator
cd mevn-character-generator
</code></pre>
<p>We'll then install the <a target="_blank" href="https://cli.vuejs.org/">Vue CLI</a> globally to help us scaffold a basic app: </p>
<pre><code class="lang-cli">npm install -g @vue/cli
</code></pre>
<p>Next, we'll use the Vue CLI to create a new app called "Client" within our mevn-character-generator directory:</p>
<pre><code class="lang-cli">vue create client
</code></pre>
<p>You can just hit "enter" at the prompt to keep going.</p>
<p>We can run our app by first navigating into the /client folder:</p>
<pre><code class="lang-cli">cd client
npm run serve
</code></pre>
<p>When the script has completed running, we can now open a browser page and navigate to the URL indicated by our terminal (usually http://localhost:8080 or 8081).  We should see something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Vue-Template.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Nice! The Vue CLI has scaffolded a basic app for us, and is rendering it right into the browser. It'll also reload the page automatically upon file changes, and throw errors if something in the code looks amiss.</p>
<p>Let's open the project directory in our code editor to take a look at the file structure, which should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Client-Directory.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you're OCD like I am, you can go ahead and delete the "favicon.ico" file and "/assets" folder as we won't need them for this project.</p>
<p>Diving into /src/main.js, we see:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Vue <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App.vue'</span>

Vue.config.productionTip = <span class="hljs-literal">false</span>

<span class="hljs-keyword">new</span> Vue({
  <span class="hljs-attr">render</span>: <span class="hljs-function"><span class="hljs-params">h</span> =&gt;</span> h(App),
}).$mount(<span class="hljs-string">'#app'</span>)
</code></pre>
<p>This file is the main entry point for our client. It tells the browser to mount our App.vue file to the div with id "#app" in /public/index.html.</p>
<p>Let's look at /src/App.vue (I've omitted some code for readability):</p>
<pre><code class="lang-javascript">&lt;template&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Vue logo"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./assets/logo.png"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">HelloWorld</span> <span class="hljs-attr">msg</span>=<span class="hljs-string">"Welcome to Your Vue.js App"</span>/&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">import</span> HelloWorld <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/HelloWorld.vue'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'App'</span>,
  <span class="hljs-attr">components</span>: {
    HelloWorld
  }
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span>
#app {
...
}
<span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span></span>
</code></pre>
<p>App.vue is a typical Vue <a target="_blank" href="https://vuejs.org/v2/guide/components.html">component</a>, with , </p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Version a REST API ]]>
                </title>
                <description>
                    <![CDATA[ If you're not very familiar with APIs, you might be wondering...why all the fuss about API versioning?  If you've been burned by API changes, you're probably the one fussing. If you are a maintainer of an API, you might also be fussing about trying t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-version-a-rest-api/</link>
                <guid isPermaLink="false">66bccb6c4a4c0beb784641d6</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data contracts ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ versioning ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tim Kleier ]]>
                </dc:creator>
                <pubDate>Tue, 03 Mar 2020 01:17:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/03/Art-Exhibit-Blog-Banner.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're not very familiar with APIs, you might be wondering...why all the fuss about API versioning? </p>
<p>If you've been burned by API changes, you're probably the one fussing. If you are a maintainer of an API, you might also be fussing about trying to field challenging questions like these:</p>
<pre><code># Is <span class="hljs-built_in">this</span> version <span class="hljs-number">2</span> <span class="hljs-keyword">of</span> just products or <span class="hljs-keyword">of</span> the entire API?
<span class="hljs-regexp">/v2/</span>products

# What catalyzed the change between v1 and v2? How are they different?
<span class="hljs-regexp">/v1/</span>products
/v2/products
</code></pre><p>These questions around versioning are not easy to answer. It's not always clear as to what <code>v1</code> or <code>v2</code> is referring to. And we should not just make a second version of an endpoint when the first no longer <em>seems</em> to suffice. </p>
<p>There are clear reasons <em>why</em> your API needs to have versioning, and there are clear strategies for <em>how</em> to effectively navigate API changes. </p>
<p>However, I have found that most developers--including myself, until I learned some lessons the hard way--are not aware of these reasons and strategies.</p>
<p>This article seeks to highlight those reasons for versioning and strategies for accomplishing it. We're going to assume a <a target="_blank" href="https://restfulapi.net/">REST</a> API context, as it's a standard for many APIs, and focus on the <em>versioning</em> aspect.</p>
<h2 id="heading-what-is-versioning">What is Versioning?</h2>
<p>We should start with level-setting on what is meant by the term "API versioning". Here's our working definition:</p>
<blockquote>
<p>API versioning is the practice of transparently managing changes to your API.</p>
</blockquote>
<p>Versioning is effective communication around changes to your API, so consumers know what to expect from it. You are delivering data to the public in some fashion and you need to communicate when you change the way that data is delivered.</p>
<p>What this boils down to, in the nitty gritty, is managing data contracts and breaking changes. The former is the primary building block of your API and the latter reveals why versioning is needed.</p>
<h3 id="heading-data-contracts">Data Contracts</h3>
<p>An API is an Application Programming <strong>Interface</strong>, and an interface is a <em>shared</em> boundary to exchange information. The data contract is the heart of this interface.</p>
<blockquote>
<p>A data contract is an agreement on the shape and general content of the request and/or response data. </p>
</blockquote>
<p>To illustrate a data contract, here's a basic JSON response body:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: [
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Product 1"</span>
    },
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Product 2"</span>
    }
  ]
}
</code></pre>
<p>It's an object with a <code>data</code> property that is an array (list) of products, each with an <code>id</code> and <code>name</code> property. But the <code>data</code> property could have just as easily been called <code>body</code>, and the <code>id</code> property on each product could have been a GUID instead of an integer. If a single product was being returned, <code>data</code> could be an object instead of an array. </p>
<p>These seemingly subtle changes would have made for a different agreement, a different contract, regarding the "shape" of the data. The data shape could apply to property names, data types, or even the expected format (JSON vs. XML).</p>
<h2 id="heading-why-is-versioning-needed">Why is Versioning Needed?</h2>
<p>With APIs, something as simple as changing a property name from <code>productId</code> to <code>productID</code> can break things for consumers. This very thing happened to our team last week. </p>
<p>Thankfully, we had tests to catch changes to the API contract. However, we shouldn't have needed those tests, because the maintainers of the API should have known this would be a breaking change.</p>
<h3 id="heading-breaking-changes">Breaking Changes</h3>
<p>This was a breaking change to the agreed upon data contract because their change forced us to change our application as well. </p>
<blockquote>
<p><em>What constitutes a "breaking change" in an API endpoint?</em> Any change to your API contract that forces the consumer to also make a change. </p>
</blockquote>
<p>Breaking changes primarily fit into the following categories:</p>
<ol>
<li>Changing the request/response format (e.g. from XML to JSON)</li>
<li>Changing a property name (e.g. from <code>name</code> to <code>productName</code>) or data type on a property (e.g. from an integer to a float)</li>
<li>Adding a required field on the request (e.g. a new required header or property in a request body)</li>
<li>Removing a property on the response (e.g. removing <code>description</code> from a product)</li>
</ol>
<h3 id="heading-api-change-management">API Change Management</h3>
<p>It is never wise or kind to force consumers of an API to make a change. If you must make a breaking change, that's what versioning is for, and we'll cover the most effective ways to version your application and endpoints. </p>
<p>But first let's briefly discuss how to avoid breaking changes in the first place. We could call this API change management.</p>
<p>Effective change management in the context of an API is summarized by the following principles:</p>
<ul>
<li>Continue support for existing properties/endpoints</li>
<li>Add new properties/endpoints rather than changing existing ones</li>
<li>Thoughtfully sunset obsolete properties/endpoints</li>
</ul>
<p>Here's an example that demonstrates all three of these principles in the context of the response for requesting user data:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Carlos Ray Norris"</span>,     <span class="hljs-comment">// original property</span>
    <span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"Carlos"</span>,           <span class="hljs-comment">// new property</span>
    <span class="hljs-attr">"lastName"</span>: <span class="hljs-string">"Norris"</span>,            <span class="hljs-comment">// new property</span>
    <span class="hljs-attr">"alias"</span>: <span class="hljs-string">"Chuck"</span>,                <span class="hljs-comment">// obsolete property</span>
    <span class="hljs-attr">"aliases"</span>: [<span class="hljs-string">"Chuck"</span>, <span class="hljs-string">"Walker"</span>]   <span class="hljs-comment">// new property</span>
  },
  <span class="hljs-attr">"meta"</span>: {
    <span class="hljs-attr">"fieldNotes"</span>: [
      {
        <span class="hljs-attr">"field"</span>: <span class="hljs-string">"alias"</span>,
        <span class="hljs-attr">"note"</span>: <span class="hljs-string">"Sunsetting on [future date]. Please use aliases."</span>
      }
    ]
  }
}
</code></pre>
<p>In this example, <code>name</code> was an original property. The <code>firstName</code> and <code>lastName</code> fields are being implemented to provide a more granular option, in the event that the consumer wants to display "Mr. Norris" with some string interpolation but without having to parse the <code>name</code> field. However, the <code>name</code> property will be supported in an ongoing fashion. </p>
<p><code>alias</code>, on the other hand, is going to be deprecated in favor of the <code>aliases</code> array--because Chuck has so many aliases--and there is a note in the response to indicate the sunsetting time frame.</p>
<h2 id="heading-how-do-you-version-an-api">How Do You Version an API?</h2>
<p>These principles will take a long way in navigating changes to your API without needing to roll a new version. However, sometimes it's avoidable, and if you need a brand new data contract, you'll need a new version of your endpoint. So you'll need to communicate that to the public in some way.</p>
<p>As an aside, do note that we're not talking about the version of the underlying code base. So if you're using <a target="_blank" href="https://semver.org/">semantic versioning</a> for your application that also supports a public API, you will likely want to separate those versioning systems.</p>
<p>How do you create a new version of your API? What are the different methods for doing so? You'll need to determine what <em>type</em> of versioning strategy you want to take in general, and then as you develop and maintain your API, you'll need to determine the <em>scope</em> of each version change.</p>
<h3 id="heading-scope">Scope</h3>
<p>Let's tackle scope first. As we explored above, sometimes data contracts will be compromised by a breaking change, and that means we'll need to provide a new version of the data contract. That could mean a new version of an endpoint, or it could mean a change at a more global application scope.</p>
<p>We can think of levels of scope change within a tree analogy:</p>
<ul>
<li><strong>Leaf</strong> - A change to an isolated endpoint with no relationship to other endpoints</li>
<li><strong>Branch</strong> - A change to a group of endpoints or a resource accessed through several endpoints</li>
<li><strong>Trunk</strong> - An application-level change, warranting a version change on most or all endpoints</li>
<li><strong>Root</strong> - A change affecting access to all API resources of all versions</li>
</ul>
<p>As you can see, moving from leaf to root, the changes become progressively more impactful and global in scope.</p>
<p>The <em>leaf</em> scope can often be handled through effective API change management. If not, simply create a new endpoint with the new resource data contract.</p>
<p>A <em>branch</em> is a little trickier, depending on just how many endpoints are affected by the data contract change on the resource in question. If the changes are relatively confined to a clear group of related endpoints, you could potentially navigate this by introducing a new name for the resource and updating your docs accordingly.</p>
<pre><code># variants, which has a breaking change, is accessed on multiple routes
/variants
/products/:id/variants

# we introduce product-variants instead
/product-variants
/products/:id/product-variants
</code></pre><p>A <em>trunk</em> refers to application-level changes that are often a result of a change in one of the following categories:</p>
<ul>
<li>Format (e.g. from <a target="_blank" href="https://www.w3schools.com/xml/xml_whatis.asp">XML</a> to <a target="_blank" href="https://www.w3schools.com/js/js_json_intro.asp">JSON</a>)</li>
<li>Specification (e.g. from an in-house one to <a target="_blank" href="https://www.freecodecamp.org/news/p/ccead735-3d4a-4304-b4e2-57b78ce59156/jsonapi.org">JSON API</a> or <a target="_blank" href="https://www.openapis.org/">Open API</a>)</li>
<li>Required headers (e.g. for authentication/authorization)</li>
</ul>
<p>These will necessitate a change in your overall API version, so you should plan carefully and execute the transition well. </p>
<p>A <em>root</em> change will force you to go one step further in ensuring that all consumers of all versions of your API are aware of the change.</p>
<h2 id="heading-types-of-api-versioning">Types of API Versioning</h2>
<p>As we turn to different types of API versioning, we'll want to use these insights into varying scopes of API changes to evaluate the types. Each approach has its own set of strengths and weaknesses in addressing changes based on their scope.</p>
<p>There are several methods for managing the version of your API. URI path versioning is the most common.</p>
<h3 id="heading-uri-path">URI Path</h3>
<pre><code>http:<span class="hljs-comment">//www.example.com/api/v1/products</span>
http:<span class="hljs-comment">//api.example.com/v1/products</span>
</code></pre><p>This strategy involves putting the version number in the path of the URI, and is often done with the prefix "v". More often than not, API designers use it to refer to their application version (i.e. "trunk") rather than the endpoint version (i.e. "leaf" or "branch"), but that's not always a safe assumption.</p>
<p>URI path versioning implies orchestrated releases of application versions that will require one of two approaches: maintaining one version while developing a new one or forcing consumers to wait for new resources until the new version is released. It also means you'd need to carry over any non-changed endpoints from version to version. However, for APIs with relatively low volatility, it's still a decent option.</p>
<p>You would likely not want to relate your version number to that of the endpoint or resource, because it would easily result in something like a <code>v4</code> of <code>products</code> but a <code>v1</code> of <code>variants</code>, which would be rather confusing.</p>
<h3 id="heading-query-params">Query Params</h3>
<pre><code>http:<span class="hljs-comment">//www.example.com/api/products?version=1</span>
</code></pre><p>This type of versioning adds a query param to the request that indicates the version. Very flexible in terms of requesting the version of the resource you'd like at the "leaf" level, but it holds no notion of the overall API's version and lends itself to the same out-of-sync issues mentioned in the above comment on endpoint-level versioning of the URI path.</p>
<h3 id="heading-header">Header</h3>
<pre><code>Accept: version=<span class="hljs-number">1.0</span>
</code></pre><p>The header approach is one that provides more granularity in serving up the requested version of any given resource. </p>
<p>However, it's buried in the request object and isn't as transparent as the URI path option. It's also still hard to tell whether <code>1.0</code> refers to the version of the endpoint or the API itself.</p>
<h3 id="heading-integrating-types">Integrating Types</h3>
<p>Each of these approaches seem to have the weakness of either favoring a "leaf" or "trunk" scope, but not supporting both. </p>
<p>If you need to maintain the overall API version and also provide support for multiple versions of resources, consider a blend of the URI Path and Query Params types, or a more advanced Header approach.</p>
<pre><code># URI path and query params combo
<span class="hljs-attr">http</span>:<span class="hljs-comment">//api.example.com/v1/products?version=1</span>
http:<span class="hljs-comment">//api.example.com/v1/products?version=2</span>

# Extended headers, <span class="hljs-keyword">for</span> http:<span class="hljs-comment">//api.example.com/products</span>
Accept: api-version=<span class="hljs-number">1</span>; resource-version=<span class="hljs-number">1</span>
<span class="hljs-attr">Accept</span>: api-version=<span class="hljs-number">1</span>; resource-version=<span class="hljs-number">2</span>
</code></pre><h2 id="heading-conclusion">Conclusion</h2>
<p>We've covered a lot of ground here, so let's recap:</p>
<ul>
<li>API versioning is the practice of transparently managing changes to your API.</li>
<li>Managing an API boils down to defining and evolving data contracts and dealing with breaking changes.</li>
<li>The most effective way to evolve your API without breaking changes is to follow effective API change management principles.</li>
<li>For most APIs, versioning in the URI path is the most straightforward solution.</li>
<li>For more complex or volatile APIs, you can manage varying scopes of changes by employing an integration of URI path and query params approaches.</li>
</ul>
<p>Although these principles should provide clear direction in how to effectively manage change to your APIs, evolving an API is potentially more of an art than a science. It requires thought and foresight to create and maintain a reliable API.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Node.js Development with modern JavaScript using FortJs ]]>
                </title>
                <description>
                    <![CDATA[ By Ujjwal Gupta Introduction Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nodejs-development-with-modern-javascript-using-fortjs/</link>
                <guid isPermaLink="false">66d461728812486a37369d6c</guid>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 23 Oct 2019 02:37:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-20-36-31-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ujjwal Gupta</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the development even easier and faster.</p>
<p>But there are a few challenges in Nodejs development:</p>
<ul>
<li>Nodejs is all about callbacks, and with more and more callbacks you end up with a situation called callback hell.</li>
<li>Writing readable code.</li>
<li>Writing maintainable code.</li>
<li>You don't get much intellisense support which makes development slow.</li>
</ul>
<p>If you are quite experienced and have a good knowledge of Nodejs, you can use different techniques and try to minimize these challenges.</p>
<p>The best way to solve these problems is by using modern JavaScript ES6, ES7 or TypeScript, whatever you feel comfortable with. I recommend TypeScript, because it provides intillisense support for every word of code which makes your development faster.</p>
<p>So I created a framework called <a target="_blank" href="http://fortjs.info/">FortJs</a> which is very easy to learn and use. FortJs enables you to write server-side code using ES6 or TypeScript which is modular, secure, and pretty much just beautiful and readable.</p>
<h2 id="heading-features">Features</h2>
<p>Some of the important features of FortJs are:  </p>
<ul>
<li>Based on <a target="_blank" href="https://github.com/ujjwalguptaofficial/fort">Fort</a> architecture. </li>
<li>MVC Framework and follows OOPS approach so everything is class and object.</li>
<li>Provides components - Wall, Shield and Guard. Components help modularize the application.</li>
<li>Uses ES6 async/await or promise for executing asychronous code.</li>
<li>Everything is configurable - you can configure your session store, view engine, websocket etc.</li>
<li>Dependency Injection.</li>
<li>Everything can be unit tested, so you can use a <a target="_blank" href="https://guide.freecodecamp.org/agile/test-driven-development/">TDD</a> approach.</li>
</ul>
<h2 id="heading-lets-code">Let's Code</h2>
<p>In this article I am going to create a REST API using FortJs and ES6. But you can use the same code and steps to implement using TypeScript too.</p>
<h3 id="heading-project-setup">Project Setup</h3>
<p>FortJs provides a CLI - fort-creator. This helps you set up the project and develop faster. Let's use the CLI to develop.</p>
<p> Perform the below steps sequentially:</p>
<ul>
<li>Open your terminal or command prompt.</li>
<li>Install <strong>fort-creator</strong> globally - run the command "npm i fort-creator -g". Note: Make sure you have Nodejs installed in your system.</li>
<li>Create a new project - run the command "fort-creator new my-app". Here “my-app” is the name of the app, so you can choose any name. The CLI will prompt you to choose the language with two options: TypeScript and JavaScript. Choose your language by using the arrow keys and press enter - i have chosen JavaScript. It will take some time to create the project, so please wait until you see "new project my-app created".</li>
<li>Enter into the project directory - "cd my-app".<br>Start the development server with live reloading - run the command "fort-creator start".</li>
<li>Open the browser and type the URL - <a target="_blank" href="http://localhost:4000/">http://localhost:4000/</a>.  </li>
</ul>
<p>You should see something like this in the browser.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-20-36-31.png" alt="Image" width="600" height="400" loading="lazy">
<em>FortJs starter page</em></p>
<p>Let's understand how this page is rendered:</p>
<ul>
<li>Open the project folder in your favourite code editor. I am going to use VS Code. You will see many folders inside project root such as controllers, views, etc. Every folder is grouped by their use - for example, the controllers folder contains all controllers and the views folder contains all views.</li>
<li>Open the controllers folder -&gt; Inside the controllers, you will see a file name - default_controller. Let's open it and observe the code. The file contains a class DefaultController - this is a <a target="_blank" href="http://fortjs.info/tutorial/controller/">controller</a> class and it contains methods which return some http response.</li>
<li>Inside the class DefaultController, you will see a method 'index' - this is the one which is rendering current output to the browser. The method is known as <a target="_blank" href="http://fortjs.info/tutorial/worker/">worker</a> in FortJs because they do some kind of work and return the result as an http response. Let's observe the index method code:  </li>
</ul>
<pre><code><span class="hljs-keyword">const</span> data = {  
    <span class="hljs-attr">title</span>: title  
}  
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> viewResult(<span class="hljs-string">'default/index.html'</span>, data);  
<span class="hljs-keyword">return</span> result;
</code></pre><p>It creates a data object and passes that object into the <strong>viewResult</strong> method. The <strong>viewResult</strong> method takes two parameters - the view location and view data. The work of <strong>viewResult</strong> is to render the view and return a response, which we are seeing in the browser.</p>
<ul>
<li>Let's find the view code and understand it. Open the views folder - &gt; open default folder - &gt; open index.html. This is our view code. It is simple HTML code along with some mustache syntax. The default view engine for Fortjs is mustache.</li>
</ul>
<p>I hope you have understood the project architecture. If you are having any difficulties or doubts, please feel free to ask in the comments section.</p>
<p>Now we will move to next part of this article where we will learn how to create a simple rest API.</p>
<h2 id="heading-rest">REST</h2>
<p>We are going to create a REST endpoint for entity user - which will perform CRUD operations for the user such as adding a user, deleting a user, getting a user, and updating a user.</p>
<p>According to REST:</p>
<ol>
<li>Adding user - should be done using the http method "<code>POST</code>"</li>
<li>Deleting user - should be done using the http method "<code>REMOVE</code>"</li>
<li>Getting user - should be done using the http method "<code>GET</code>"</li>
<li>Updating user - should be done using the http method "<code>PUT</code>"</li>
</ol>
<p>For creating an endpoint, we need to create a Controller similar to the default controller explained earlier.</p>
<p>Execute the command  "<code>fort-creator add</code>". It will ask you to "Choose the component to add ?" Choose Controller &amp; press <strong>enter</strong>. Enter the controller name "User" and press <strong>enter</strong>.</p>
<p>Now that we have created the user controller we need to inform FortJs by adding it to routes. The route is used to map our controller to a path.</p>
<p>Since our entity is user, "<code>/user</code>" will be a good route. Let's add it. Open routes.js inside the root directory of the project and add <code>UserController</code> to routes.</p>
<p>After adding UserController, routes.js will look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { DefaultController } <span class="hljs-keyword">from</span> <span class="hljs-string">"./controllers/default_controller"</span>;
<span class="hljs-keyword">import</span> { UserController } <span class="hljs-keyword">from</span> <span class="hljs-string">"./controllers/user_controller"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> routes = [{
    <span class="hljs-attr">path</span>: <span class="hljs-string">"/*"</span>,
    <span class="hljs-attr">controller</span>: DefaultController
},
{
    <span class="hljs-attr">path</span>: <span class="hljs-string">"/user"</span>,
    <span class="hljs-attr">controller</span>: UserController
}]
</code></pre>
<p>So when an http request has the path "/user" then UserController will be called. </p>
<p>Let's open the url - <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a>.</p>
<p>Note: If you have stopped FortJs while adding the controller, please start it again by running the cmd - <code>fort-creator start</code></p>
<p>And you see a white page right?</p>
<p>This is because we are not returning anything from the index method and thus we get a blank response. Let's return a text "Hello World" from the index method. Add the below code inside the index method and save:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> textResult(<span class="hljs-string">'Hello World'</span>);
</code></pre>
<p>Refresh the url - <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a></p>
<p>And you see "Hello World" right?</p>
<p>Now, let's convert "UserController" to a REST API. But before writing code for the REST API, let's create a dummy service which will do CRUD operations for users.</p>
<h3 id="heading-service">Service</h3>
<p>Create a folder called “services” and then a file “user_service.js” inside the folder. Paste the below code inside the file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> store = {
    <span class="hljs-attr">users</span>: [{
        <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
        <span class="hljs-attr">name</span>: <span class="hljs-string">"ujjwal"</span>,
        <span class="hljs-attr">address</span>: <span class="hljs-string">"Bangalore India"</span>,
        <span class="hljs-attr">emailId</span>: <span class="hljs-string">"ujjwal@mg.com"</span>,
        <span class="hljs-attr">gender</span>: <span class="hljs-string">"male"</span>,
        <span class="hljs-attr">password</span>: <span class="hljs-string">"admin"</span>
    }]
}

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserService</span> </span>{
    getUsers() {
        <span class="hljs-keyword">return</span> store.users;
    }

    addUser(user) {
        <span class="hljs-keyword">const</span> lastUser = store.users[store.users.length - <span class="hljs-number">1</span>];
        user.id = lastUser == <span class="hljs-literal">null</span> ? <span class="hljs-number">1</span> : lastUser.id + <span class="hljs-number">1</span>;
        store.users.push(user);
        <span class="hljs-keyword">return</span> user;
    }

    updateUser(user) {
        <span class="hljs-keyword">const</span> existingUser = store.users.find(<span class="hljs-function"><span class="hljs-params">qry</span> =&gt;</span> qry.id === user.id);
        <span class="hljs-keyword">if</span> (existingUser != <span class="hljs-literal">null</span>) {
            existingUser.name = user.name;
            existingUser.address = user.address;
            existingUser.gender = user.gender;
            existingUser.emailId = user.emailId;
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    getUser(id) {
        <span class="hljs-keyword">return</span> store.users.find(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id === id);
    }

    removeUser(id) {
        <span class="hljs-keyword">const</span> index = store.users.findIndex(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id === id);
        store.users.splice(index, <span class="hljs-number">1</span>);
    }
}
</code></pre>
<p>The above code contains a variable store which contains a collection of users. The method inside the service does operations like add, update, delete, and get on that store.</p>
<p>We will use this service in REST API implementation.</p>
<h3 id="heading-get">GET</h3>
<p>For the route "/user" with the http method "GET", the API should return a list of all users. </p>
<p>In order to implement this, let's rename the "index" method inside user_controller.js to "getUsers" making it semantically correct. Then paste the below code inside the method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> service = <span class="hljs-keyword">new</span> UserService();
<span class="hljs-keyword">return</span> jsonResult(service.getUsers());
</code></pre>
<p>Now user_controller.js looks like this:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Controller, DefaultWorker, Worker, textResult, jsonResult } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;
<span class="hljs-keyword">import</span> { UserService } <span class="hljs-keyword">from</span> <span class="hljs-string">"../services/user_service"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{

    @DefaultWorker()
    <span class="hljs-keyword">async</span> getUsers() {
        <span class="hljs-keyword">const</span> service = <span class="hljs-keyword">new</span> UserService();
        <span class="hljs-keyword">return</span> jsonResult(service.getUsers());
    }
}
</code></pre>
<p>Here, we are using the decorator DefaultWorker. The DefaultWorker does two things: it adds the route "/" &amp; the http method "GET". It's a shortcut for this scenario. In the next part, we will use other decorators to customize the route.</p>
<p>Let's test this by calling the url <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a>. You can open this in the browser or use any http client tools like postman or curl. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-21-53-59.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Ok, so we have successfully created an end point :) .</p>
<p>Let's look again at our code and see if we can make it better: </p>
<ol>
<li>The service "UserService" is tightly coupled with Controller "UserController" which becomes a problem for unit testing "UserController". So we will use <a target="_blank" href="http://fortjs.info/tutorial/dependency-injection/">dependency injection</a> by FortJs to inject UserService.</li>
<li>We are creating an instance of "UserService" every time the method getUsers is called. But what we need from "UserService" is a single object and then call the "UserService" method from the object. </li>
</ol>
<p>So if we can somehow store an object of "UserService" then we can make our code faster (because calling new does some work under the hood). For this we will use the singleton feature of FortJs.</p>
<p>Let's change the user_controller.js code by the below code: </p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Controller, DefaultWorker, Worker, textResult, jsonResult, Singleton } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;
<span class="hljs-keyword">import</span> { UserService } <span class="hljs-keyword">from</span> <span class="hljs-string">"../services/user_service"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{

    @DefaultWorker()
    <span class="hljs-keyword">async</span> getUsers(@Singleton(UserService) service) {
        <span class="hljs-keyword">return</span> jsonResult(service.getUsers());
    }
}
</code></pre>
<p>As you can see, the only change is that we are using the "Singleton" decorator in the method getUsers. This will create a singleton and inject that singleton when getUsers is called. This singleton will be available throughout the application.</p>
<p>Since service is now a parameter, we can manually pass the parameter while calling. This makes getUsers unit testable.</p>
<p>For doing unit testing or E2E testing, please read this test doc - <a target="_blank" href="http://fortjs.info/tutorial/test/">http://fortjs.info/tutorial/test/</a></p>
<h3 id="heading-post">POST</h3>
<p>Let's add a method "addUser" which will extract data from the request body and call service to add a user.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
        <span class="hljs-keyword">const</span> user = {
            <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
            <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
            <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
            <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
            <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
        };
        <span class="hljs-keyword">const</span> newUser = service.addUser(user);
        <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<blockquote>
<p>In the above code we are creating the Singleton of the UserService again. So the question is will it create another object?</p>
</blockquote>
<p>No it will be same object that was in getUser. FortJs supplies the object as a parameter when it calls the method.</p>
<p>The methods created are by default not visible for an http request. So in order to make this method visible for the http request, we need to mark this as a worker. </p>
<p>A method is marked as a worker by adding the decorator "Worker". The Worker decorator takes a list of http methods and makes that method available for only those http methods. So let's add the decorator:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Post])
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = {
        <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
        <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
        <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
        <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
        <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
    };
    <span class="hljs-keyword">const</span> newUser = service.addUser(user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<p>Now the route of this method is the same as the name of the method that is "addUser". You can check this by sending a post request to <a target="_blank" href="http://localhost:4000/user/addUser">http://localhost:4000/user/addUser</a> with user data in the body.</p>
<p>But we want the route to be "/", so that it will be a rest API. The route of the worker is configured by using the decorator "Route". Let's change the route now.</p>
<pre><code>@Worker([HTTP_METHOD.Post])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = {
        <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
        <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
        <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
        <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
        <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
    };
    <span class="hljs-keyword">const</span> newUser = service.addUser(user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre><p>Now our end point is configured for a post request. Let's test this by sending a post request to <a target="_blank" href="http://localhost:4000/user/">http://localhost:4000/user/</a> with user data in the body.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-22-43-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It returns the user created with id which is our logic. So we have created the end point for the post request, but one important thing to do is to validate the data. Validation is an essential part of any app and is very important for a backend application.</p>
<p>So far, our code is clean and readable. But if we add validation code it will become a little dirty. </p>
<p>Worry not, FortJs provides the component <a target="_blank" href="http://fortjs.info/tutorial/guard/">Guard</a> for this kind of work. A/c to the FortJs docs:</p>
<blockquote>
<p>Guard is security layer on top of Worker. It controls whether a request should be allowed to call the Worker.</p>
</blockquote>
<p>So we are going to use guard for validation of the data. Let's create the guard using fort-creator. Execute the command  <code>fort-creator add</code> and choose Guard. Enter the file name "UserValidator". There will be a file "user_validator_guard.js" created inside the guards folder. Open that file.</p>
<p>A guard has access to the body, so you can validate the data inside that. Returning null inside the method <code>check</code> means that we're allowing to call the worker. Returning anything else means block the call.</p>
<p>Let's make it clearer by writing code for the validation. Paste the below code inside the file "user_validator_guard.js":</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Guard, textResult, HTTP_STATUS_CODE } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserValidatorGuard</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Guard</span> </span>{

    <span class="hljs-keyword">async</span> check() {
        <span class="hljs-keyword">const</span> user = {
            <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
            <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
            <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
            <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
            <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
        };
        <span class="hljs-keyword">const</span> errMsg = <span class="hljs-built_in">this</span>.validate(user);
        <span class="hljs-keyword">if</span> (errMsg == <span class="hljs-literal">null</span>) {
            <span class="hljs-comment">// pass user to worker method, so that they dont need to parse again  </span>
            <span class="hljs-built_in">this</span>.data.user = user;
            <span class="hljs-comment">// returning null means - guard allows request to pass  </span>
            <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> textResult(errMsg, HTTP_STATUS_CODE.BadRequest);
        }
    }

    validate(user) {
        <span class="hljs-keyword">let</span> errMessage;
        <span class="hljs-keyword">if</span> (user.name == <span class="hljs-literal">null</span> || user.name.length &lt; <span class="hljs-number">5</span>) {
            errMessage = <span class="hljs-string">"name should be minimum 5 characters"</span>
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.password == <span class="hljs-literal">null</span> || user.password.length &lt; <span class="hljs-number">5</span>) {
            errMessage = <span class="hljs-string">"password should be minimum 5 characters"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.gender == <span class="hljs-literal">null</span> || [<span class="hljs-string">"male"</span>, <span class="hljs-string">"female"</span>].indexOf(user.gender) &lt; <span class="hljs-number">0</span>) {
            errMessage = <span class="hljs-string">"gender should be either male or female"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.emailId == <span class="hljs-literal">null</span> || !<span class="hljs-built_in">this</span>.isValidEmail(user.emailId)) {
            errMessage = <span class="hljs-string">"email not valid"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.address == <span class="hljs-literal">null</span> || user.address.length &lt; <span class="hljs-number">10</span>) {
            errMessage = <span class="hljs-string">"address length should be greater than 10"</span>;
        }
        <span class="hljs-keyword">return</span> errMessage;
    }

    isValidEmail(email) {
        <span class="hljs-keyword">var</span> re = <span class="hljs-regexp">/^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/</span>;
        <span class="hljs-keyword">return</span> re.test(<span class="hljs-built_in">String</span>(email).toLowerCase());
    }


}
</code></pre>
<p>In the above code:</p>
<ul>
<li>We have created a method validate which takes the parameter user. It validates the user &amp; returns the error message if there is a validation error, otherwise null.</li>
<li>We are validating data inside the check method, which is part of guard lifecycle. We are validating the user inside it by calling the method validate.<br>If the user is valid, then we are passing the user value by using the "data" property and returning null. Returning null means guard has allowed this request and the worker should be called.</li>
<li>If a user is not valid, we are returning an error message as a text response with the HTTP code "Bad Request". In this case, execution will stop here and the worker won't be called.</li>
</ul>
<p>In order to activate this guard for the method addUser, we need to add this on top of addUser. The guard is added by using the decorator "Guards". So let's add the guard:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Post])
@Route(<span class="hljs-string">"/"</span>)
@Guards([UserValidatorGuard])
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> newUser = service.addUser(<span class="hljs-built_in">this</span>.data.user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<p>In the above code:</p>
<ul>
<li>I have added the guard, “UserValidatorGuard” using the decorator Guards.</li>
<li>With the guard in the process, we don't need to parse the data from the body anymore inside the worker. Rather, we are reading it from this.data which we are passing from "UserValidatorGuard".</li>
<li>The method “addUser” will only be called when Guard allows, which means all data is valid.</li>
</ul>
<p>One thing to note is that the method "addUser" looks very light after using a component, and it's doing validation too. You can add multiple guards to a worker which gives you the ability to modularize your code into multiple guards and use that guard at multiple places.</p>
<blockquote>
<p>Isn't this cool :D?</p>
</blockquote>
<p>Let's try adding a user with some invalid data:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-21-37.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see in the screenshot, I have tried sending a request without a password. The result is - "password should be minimum 5 characters". So it means that guard is activated and working perfectly.</p>
<h3 id="heading-put">PUT</h3>
<p>Let’s add another method - “updateUser” with route “/” , guard “UserValidatorGuard” (for validation of user) and most important - worker with http method “PUT”.</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Put])
@Guards([UserValidatorGuard])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> updateUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = <span class="hljs-built_in">this</span>.data.user;
    <span class="hljs-keyword">const</span> userUpdated = service.updateUser(user);
    <span class="hljs-keyword">if</span> (userUpdated === <span class="hljs-literal">true</span>) {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user updated"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>);
    }
}
</code></pre>
<p>The updated code is similar to the addUser code except functionality wise it is updating the data. Here, we have reutilized UserValidatorGuard to validate data.</p>
<h3 id="heading-delete">DELETE</h3>
<p>In order to delete data, user needs to pass the id of the user. This can be passed by:</p>
<ul>
<li>Sending data in body just like we did for add &amp; update - {id:1}</li>
<li>Sending data in query string - ?id=1</li>
<li>Sending data in route - for this, we need to customize our route - "/user/1"</li>
</ul>
<p>We have already implemented getting data from body. So let's see other two ways:</p>
<p><strong>Sending Data in Query String</strong></p>
<p>Let's create a method "removeByQueryString" and paste the below code:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Delete])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> removeByQueryString(@Singleton(UserService) service) {
    <span class="hljs-comment">// taking id from query string</span>
    <span class="hljs-keyword">const</span> userId = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">this</span>.query.id);
    <span class="hljs-keyword">const</span> user = service.getUser(userId);
    <span class="hljs-keyword">if</span> (user != <span class="hljs-literal">null</span>) {
        service.removeUser(userId);
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user deleted"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>, <span class="hljs-number">404</span>);
    }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-40-34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Sending Data in Route</strong></p>
<p>You can parameterise the route by using "{var}" in a route. Let's see how.</p>
<p>Let's create another method "removeByRoute" and paste the below code:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Delete])
@Route(<span class="hljs-string">"/{id}"</span>)
<span class="hljs-keyword">async</span> removeByRoute(@Singleton(UserService) service) {

    <span class="hljs-comment">// taking id from route</span>
    <span class="hljs-keyword">const</span> userId = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">this</span>.param.id);

    <span class="hljs-keyword">const</span> user = service.getUser(userId);
    <span class="hljs-keyword">if</span> (user != <span class="hljs-literal">null</span>) {
        service.removeUser(userId);
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user deleted"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>);
    }
}
</code></pre>
<p>The above code is exactly the same as removeByQueryString except that it is extracting the id from the route and using parameter in route i.e., "/{id}" where id is parameter.</p>
<p>Let's test this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-46-42.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So we have finally created a REST API for all the funtionalities except GETting a particular user by id. I will leave that to you for practice.</p>
<h2 id="heading-points-of-interest">POINTS OF INTEREST</h2>
<p>Q: How do we add authentication to "UserController", so that any unauthenticated request can't call the "/user" end point.</p>
<p>A: There are multiple approaches for this: </p>
<ul>
<li>We can check in every worker for authentication. (BAD - so much extra work and code repetition)</li>
<li>Create a Guard component and assign to every worker . (GOOD) </li>
<li>Create a <a target="_blank" href="http://fortjs.info/tutorial/shield/">Shield</a> component and assign to controller. Shield is a security layer similar to guard but works on top of controller, so if shield rejects then controller is not initiated. (BEST)</li>
</ul>
<p>Take a look at the FortJs authentication docs - <a target="_blank" href="http://fortjs.info/tutorial/authentication/">http://fortjs.info/tutorial/authentication/</a></p>
<h2 id="heading-references">REFERENCES</h2>
<ul>
<li><a target="_blank" href="http://fortjs.info/">http://fortjs.info/</a></li>
<li><a target="_blank" href="https://medium.com/fortjs">https://medium.com/fortjs</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Here’s my follow-up to REST is the new SOAP: let’s talk about the Original REST ]]>
                </title>
                <description>
                    <![CDATA[ By Pakal de Bonchamp I’ve read the philosophical dissertations, so you don’t have to! I expected my recent article (or “hipsteresque drunken rant,” as some called it), to get a barrage of criticism, under the motto “you haven’t understood anything ab... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/follow-up-to-rest-is-the-new-soap-the-origins-of-rest-21c59d243438/</link>
                <guid isPermaLink="false">66d4608f7df3a1f32ee7f881</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 02 Feb 2018 18:59:55 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*a68QxzlHe3e3THOyKV9m8w.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Pakal de Bonchamp</p>
<p><strong>I’ve read the philosophical dissertations, so you don’t have to!</strong></p>
<p>I expected my <a target="_blank" href="https://medium.freecodecamp.org/rest-is-the-new-soap-97ff6c09896d">recent article</a> (or “hipsteresque drunken rant,” as some called it), to get a barrage of criticism, under the motto “you haven’t understood anything about REST.” It indeed happened.</p>
<p>But it also sparked interesting debates, especially on <a target="_blank" href="https://www.reddit.com/r/javascript/comments/7k2kv2/rest_is_the_new_soap_pakal_de_bonchamp_medium/?st=jb8hbpsd&amp;sh=1a3a371e">Reddit</a> and on <a target="_blank" href="https://news.ycombinator.com/item?id=15937448">Hacker News</a>. It also struck a cord in numerous developers, who felt like heretics for doubting the almightiness of REST.</p>
<p>To quote a <a target="_blank" href="https://news.ycombinator.com/item?id=15938460">particularly insightful summary</a> of the resentment:</p>
<blockquote>
<p><em>A simple RPC API spec takes minutes to define. ‘Rest’ifying takes much longer, there are a million little gotchas, no real standard. Everyone has a different opinion of how it should be done.</em></p>
<p><em>Data is spread across verbs, urls, query params, headers, and payloads. Everyone thinks everyone else doesn’t ‘get’ REST. If you try to suggest something other than REST in the office you become the subject of a witch hunt. It really is a cargo cult of pointlessness.</em></p>
<p><em>My co-workers have spent sooo much time trying to get Swagger to generate documentation correctly as well as generate client side APIs, and there are countless gotchas we are still dealing with. It really is SOAP 2.0, when a simple JSON/RPC protocol would have done fine.</em></p>
<p><em>Don’t get me started with conflating HTTP server errors with applications errors. And trying to do action-like requests with a mindset optimized for CRUD. How much time have we wasted figuring out the ‘standard’ way to do just a login API call RESTfully.</em></p>
</blockquote>
<p>On the opposite side, Phil Sturgeon, one of the main advocates of REST, released a <a target="_blank" href="https://philsturgeon.uk/api/2017/12/18/rest-confusion-explained/">response article</a> (see my <a target="_blank" href="http://disq.us/p/1oy9a9l">quick comments here</a>). I’m glad we agreed on some important points, especially that many APIs actually ought to be RPC, instead of ending as pseudo-REST patch-up jobs.</p>
<p>In the light of all this feedback, I’ve edited my initial essay quite a few times, and now a new article seems necessary to clarify the remaining points.</p>
<p>I would like to apologize in advance if the cheekiness of this post comes across as rudeness. Considering the harmfulness of the situation, I alas couldn’t content myself of a peaceful tone. No personal offense is meant in any way. So let’s get on with it.</p>
<h3 id="heading-several-shades-of-rest">Several shades of REST</h3>
<p>One difficulty of the subject is that there are several concepts behind the term “REST.”</p>
<p>1) The Founding Book of REST, i.e <a target="_blank" href="https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">the dissertation of Roy Fielding</a><br>2) The thousands of blogposts/podcasts of REST advocates (like Phil Sturgeon’s), disseminated on the Web, and explaining “how to do REST properly”<br>3) The gazillions of (self-proclaimed) RESTful webservices, publicly or privately exposed all over the Internet</p>
<p>My rant was mostly dealing with <strong>#3:</strong> the RESTish APIs that are wasting everyone’s time, for yet-to-be-demonstrated benefits. And even after reading hundreds of comments, I have to stand my ground: these APIs that I’ve met everywhere are constantly reinventing the wheel, don’t even leverage the advantages that HTTP semantics could bring (client-side caching, content negotiation, optimistic locking…), and are a lengthy pain to integrate.</p>
<p>The response article by Phil Sturgeon highlighted the main reason for this epitome of pointlessness:</p>
<blockquote>
<p>“<em>Folks everywhere are building RESTish APIs which are basically just RPC + HTTP verbs + Pretty URLs.</em>”</p>
</blockquote>
<p>Along the way, we evoked <strong>#2</strong> through some quotes of REST advocates. For the rest, as far as I’ve seen, REST bloggers/podcasters have often contradicted each other. They’ve given instructions that sounded more like tastes than wisdom lessons, have evaded the most important questions, and have made a virtue of not backing, with examples and demonstrations, their most audacious arguments: <em>“RPC causes redundant work”</em>, <em>“REST is necessary for APIs lasting decades”</em>, and of course the (in)famous <em>“The client does not need any prior knowledge of the service in order to use it.”</em></p>
<p>I’ve not yet crossed a simple page of prose summarizing how HATEOAS <em>really</em> works, and what challenges it solves for us. This is a problem in itself.</p>
<p>About contradictions…here’s an anecdote. When I showcased a simple (and gently CRUD-oriented) API, it was just to show the abnormal number of questions that had to be answered just to RESTify it. And still, numbers of commenters felt compelled to explain, with verbose documentation, how THEY would specify this API.</p>
<p>It resulted in lots of similar but incompatible protocols, some weaving standards together, some reinventing carved flintstone, and some going as far as specifying a versioned MIME type per Resource endpoint (like <em>“application/vnd.my-rest-api.v1.account-search-result+json”</em>).</p>
<p>Phil Sturgeon also answered, in his response article, these semi-rhetorical questions. The recommendations delivered made sense and seemed “up to date.” But they directly contradicted the past or present teachings of lots of other REST proponents (as well as commenters cited above) on diverse subjects: sparse fields, compounds documents, PATCH formats, DELETE payloads, and so on.</p>
<p>At least all this proved a point: when things must be done quickly and consensually, REST is not the best way to go. Still, many claimed that I was attacking “misconceptions” of REST, and directed me to this or that quote from the original dissertation. This was a way of saying that the “theory” was good, even though the “practice” was flawed. “<em>Yeah, right, communism claims the same,</em>” one might argue.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/DIOnmqtsew2du2MQ-H9Rx67Y7kny0XF6oI4y" alt="Image" width="271" height="340" loading="lazy">
<em>How <em>some</em> REST advocates view its Founding Thesis</em></p>
<p>The debate of whether a practice is RESTful or not has become a running gag in the web development ecosystem. However, for the sake of intellectual honesty, it was actually interesting to come back to the most authoritative definition of REST™ as given by the dissertation <strong>#1</strong> and related articles. It’s at least to understand how this hype started, and what can be saved from it all.</p>
<p>I hope the summaries below will be deemed faithful enough to the originals. If not, I welcome your feedback on other “misconceptions” they might contain.</p>
<h3 id="heading-what-is-the-original-rest-anyway">What is the Original REST™ anyway?</h3>
<p>Roy Fielding’s <a target="_blank" href="https://medium.com/@pakaldebonchamp/follow-up-to-rest-is-the-new-soap-the-origins-of-rest-21c59d243438">dissertation</a>, published in 2000, is naturally long (180 pages), so it’s probably not widely read among web developers.</p>
<p>Here is a breakdown of its content. As an alternative, you can also read the Introduction and Conclusion chapters of said dissertation.</p>
<ul>
<li>Chapter 1 defines architecture-related terms like elements, components, properties, styles, patterns, and so on.</li>
<li>Chapter 2 lists the key properties for a network-based architecture: user-perceived performance, network efficiency, scalability, modifiability, visibility, and reliability.</li>
<li>Chapter 3 classifies existing architectural styles (Pipe and Filter, Cache, Client-Server, Code on Demand), and shows their pros and cons regarding the key properties above.</li>
<li>Chapter 4 summarizes the requirements of the World Wide Web architecture (Low Entry Barrier, Extensibility, Distributed Hypermedia, Anarchic Scalability and so on), and explains why a dedicated architectural style is needed to guide its development, especially to evaluate proposed extensions before they are deployed.</li>
<li>Chapter 5 presents the REST architectural style: the existing styles from which it derives, its architectural elements (Resources and their Identifiers, Representations, Connectors, Components, and so on), and how all this works together regarding processes and data.</li>
<li>Chapter 6 gives an experience feedback of how REST was used to guide the development of Web protocol standards (URIs, HTTP and its numerous features and extensions), where it failed to be applied (cookies, mixing of different concerns in headers, user IDs in URIs, and so on), and the architectural lessons to be learned from the modern Web architecture.</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/RICSoTTSIx3hE6WbMEFyh-UHXdYMFmPLLxGe" alt="Image" width="324" height="205" loading="lazy">
<em>The book “An introduction to REST: Tome 1”</em></p>
<p>What do we get from this dissertation, apart from the usual <a target="_blank" href="http://whatisrest.com/rest_constraints/index">REST constraints</a>?</p>
<p>First, as expected from the <strong>introduction of an “architectural style,”</strong> it says almost nothing about HTTP methods, schemas, error handling, versioning, and all these concrete subjects which shape real-world webservices. That’s why hundreds of contradicting opinions have flowed to fill the hole, and that’s why it’s weird to sometimes hear that REST is “<em>precisely specified</em>” by this dissertation.</p>
<p>Second, REST was formalized to give a <strong>theoretical backbone to the development of the World Wide Web.</strong> It mixes lots of existing architectural styles, and inherits from their benefits and drawbacks, for the purpose of designing an <strong>Internet-scale distributed hypermedia system</strong>.</p>
<p><strong>And it works.</strong></p>
<ul>
<li>On the web, we are happy that all webpages speak HTTP, display themselves with a GET, and handle forms with GET or POST [Uniform Interface]</li>
<li>On the web, we’re happy that our browser understands hundreds of content types (HTML, images, CSS, fonts, Javascript, RSS…), and handles them according to numerous built-in rules (caching, display, security…) [Self-Descriptive Messages]</li>
<li>On the web, we’re happy to have in-browser caching, content delivery networks, and other forms of shared caches, helping to speed up loading time and absorb traffic peaks (like “Slashdot effects”). Even though a quick ctrl+F5 is sometimes needed to fix weird behaviors of webpages. [Layered System &amp; Caching]</li>
<li>On the web, we’re happy that proxies and firewalls understand web protocols, and let them flow, while blocking dubious TCP/UDP connections. [Visibility]</li>
<li>On the web, we’re happy that scripts can be delivered by the server for each page, since browsers have, by themselves, no clue about how to add dynamics to provided HTML [Code-On-Demand]</li>
</ul>
<p>One point <a target="_blank" href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5">evoked but not detailed in the dissertation</a> is “<strong>Hypermedia As The Engine Of Application State</strong>” <strong>(HATEOAS).</strong> In complementary articles, Roy Fielding explained the concept of “<em>hypermedia controls,</em>” also called “<em>affordances:</em>” some kinds of glorified links, advertising to the client “what it can do next.” And he declared (a little late?) that these are not mere options, but that HATEOAS is at the very core of REST.</p>
<blockquote>
<p>When I say Hypertext, I mean … The simultaneous presentation of information and controls such that the information becomes the affordance through which the user obtains choices and selects actions. Hypertext does not need to be HTML on a browser: machines can follow links when they understand the data format and relationship types (<a target="_blank" href="http://roy.gbiv.com/talks/200711_REST_ApacheCon.pdf">source</a>).</p>
<p><em>Information and actions, displayed up to a user through a self-documenting format of awesomeness, with a selection of links that turn a well-tuned client into a crawler instead of just being a CRUD exchange… well that’s the whole point of REST (<a target="_blank" href="https://blog.apisyouwonthate.com/representing-state-in-rest-and-graphql-9194b291d127">source</a>).</em></p>
<p><em>Naturally, that is where I have to explain why “hypermedia as the engine of application state” is a REST constraint. Not an option. Not an ideal. Hypermedia is a constraint. As in, you either do it or you aren’t doing REST (<a target="_blank" href="https://www.infoq.com/articles/roy-fielding-on-versioning/">source</a>).</em></p>
<p><em>A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API) (<a target="_blank" href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">source</a>).</em></p>
</blockquote>
<p>Regarding this aspect too, the Web seems RESTful. From the homepage of a website, users and webspiders are able to navigate it effortlessly, and handle related medias (images, stylesheets, scripts, and so on) that are discovered along the way. Although URLs change over time and forms are added and removed, websites don’t need version numbers, and it’s fine.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/8TXoDNwDHiJFQU4enox2C8z7PLnmBhzPlty8" alt="Image" width="680" height="550" loading="lazy">
<em>When I realized that the main HATEOAS example was just the world wide web</em></p>
<p>We thus see that the original REST™ is a powerful architectural style, providing big control to servers over their clients, and offering a crawlable ecosystem of editable hypermedia.</p>
<p>Now, what about your APIs? Do they aim at being “<em>Internet-scale distributed hypermedia systems,</em>” too?</p>
<h3 id="heading-the-hazardous-and-often-unnecessary-holy-grail">The hazardous and (often) unnecessary Holy Grail</h3>
<p>You might have heard about the <a target="_blank" href="https://martinfowler.com/articles/richardsonMaturityModel.html">Richardson Maturity Model</a>. It evaluates the level of RESTfulness of your API, depending on whether it uses proper resources (Level 1), verbs (Level 2), and hypermedia controls (Level 3). This model might give you the feeling that some “RESTish” APIs of yours are meant to evolve on these “<em>steps toward the glory of REST</em>” (as Martin Fowler describes it). Bad news, this most probably won’t occur.</p>
<p>Yes, you can fake RESTfulness by mapping your server functions to Resource URLs. Yes, you can fake it further by mapping your operations to the closest HTTP verbs. But when it’s time to reach the final level, to really have a self-descriptive, crawlable, hypermedia-driven application, you’ll have to realize the harsh truth: your API is not RESTful, it has never been, and it never will be. It actually has less chances to attain “True RESTfulness” than a slug has to become a butterfly.</p>
<p>Remember the quotes from Roy Fielding in the previous section? His definition of REST is all about HATEOAS. But it’s an extremely ambitious statement.</p>
<p>It means you should forget meaningless MIME types like “text/xml” or “text/json,” and use specific content types, backed by contracts, and recognizable by API consumers. It means that unless a full-fledged RESTful protocol already exists for your precise use case, you’ll have to write RFC/IETF-style drafts to describe the semantics of your specific content types. You’ll have to design a crawler-enabled hypermedia system, and specify the meaning of its miscellaneous “affordances.” And you’ll probably have to provide client implementations to your customers, in their own programming languages, since they have other things to do than follow such herculean endeavors.</p>
<p>All this is huge specification and implementation work. For rather light benefits. And worrisome drawbacks.</p>
<p>Yes, this enables server-side developers to keep control of their URL structure without redirections (<em>today I’ll rename “users/” to “accounts/” — it’s smoother</em>), but at what cost? Unless you constantly generate new URLs to prevent it, I bet your API consumers will hardcode URLs anyway, to avoid this extra layer of complexity (recognition of affordances, URL traversal caching etc.)</p>
<p>Yes, this enables the server to control available actions, when the end consumer is a human. But what about User eXperience? The arbitrary showing and masking of affordances by the server is a scary concept. When a “delete” button is missing on a <a target="_blank" href="https://en.wikipedia.org/wiki/Single-page_application">SPA</a>, I want to know why. And if I ask my REST-crawler program to create “this” resource, I’d rather have him fail with a proper remote error message, than say “<em>sorry, couldn’t find the affordance for that.</em>” Actions can be prevented by security rules, missing dependencies, concurrent tasks, and other issues. We have the right to know what’s going on, and “affordances,” in their current form, miss this crucial feature.</p>
<p>Also, what about machine-to-machine interactions? If API evolvability is key, how does the consumer program understand new fields and new affordances? Roy Fielding <a target="_blank" href="https://www.infoq.com/articles/roy-fielding-on-versioning/">answers</a> “<em>That is where code-on-demand shines.</em>” No way. No way you’re dynamically injecting your remote code into my Python program anytime soon.</p>
<p>After reading hundreds of pages on the REST/HATEOAS subject, I’ve rarely been so unimpressed. Reaching LEVEL 3 of RESTfulness was supposed to be an epiphany. I rather have the deep feeling that the remedy is worse than the disease.</p>
<p>Now, some people argue that Roy Fielding is pushing the concept too far, that “<strong>lightweight REST</strong>” (i.e “Richardson Maturity Level 2,” without Hypermedia Controls) is the real goal to head for.</p>
<p>But still, I bet you actually do not need any of this.</p>
<ul>
<li>You (most probably) do not want code-on-demand. You want your clients to read your specs, and call your API precisely as you (and they) intend it.</li>
<li>You (most probably) do not want network-level visibility. On the contrary, you want as much TLS encryption as possible.</li>
<li>You (most probably) do not want shared caches or client-side caching. On the contrary, remote caches are amongst your worst enemies. And if your API consumers are not browsers, they typically ignore caching headers anyway.</li>
<li>You (most probably) can do without content negotiation, and other HTTP features more or less bundled with REST best practices (you know, for Representation versus Resource). Every up-to-date language can understand formats like Xml and Json.</li>
<li>You (most probably) do not want to expose Resources for CRUD operations, and use these awkward men-in-the-middle to trigger actual operations in your applications.</li>
</ul>
<p>All you (most probably) want is to expose a bunch of your server-side functionalities to remote browsers or servers. In a quick, elegant, robust, way.</p>
<p><strong>Your API (most probably) screams “RPC”. And in this case, not even a skyscraper-sized shoehorn will allow it to fit into the very ambitious, but rarely relevant, REST Architectural Style.</strong></p>
<p>For sure, you might need this or that property of HTTP. For example, you might want to use the GET method and different URIs for your Ajax-originated read-only operations to benefit from browser-side caching. Or you might want to expose your database as CRUD-over-HTTP to leverage generic implementations (like Active Record style clients for JsonAPI protocol).</p>
<p>But whatever your needs are, <em>life is short</em>. You do not need to start from an abstract “set of guidelines” like REST constraints. You had better seek a <strong>turnkey protocol</strong>, matching the needs you really have.</p>
<p>There are tons of such solutions (mostly non-RESTful), for lightweight RPC, CRUD, pub/sub, job queues, remote filesystems, data querying/filtering, high performance computing, and bi-directional messaging. Rarely, you’ll have to innovate — add new capabilities to a protocol, or use hybrid approaches. But beginning to “turn verbs into nouns” or following abstract principles as dogmas is the last thing you need to do.</p>
<p>Please note, by the way, that CRUD can also be done as a mere subset of RPC. Webservices are usually not coded in C language anymore, so if you see one more wanderer arguing that “<em>it’s awful to have to code so many boilerplate CRUD functions</em>”, please enlighten them with this high-technology API.</p>
<pre><code>create(type, **params) -&gt; id
retrieve(type, id, **params)
update(type, id, **params)
<span class="hljs-keyword">delete</span>(type, id, **params)
</code></pre><p>Along your (most probably) RESTless way, you’ll meet dozens of adamant speeches, claiming that only REST can grant you scalability and longevity. There is little need to disprove what has never been proven. All I can judge, from personal experience, is that:</p>
<ul>
<li>A well configured database and a simple server-side cache are enough for 99% of webservices; an old wisdom says <em>premature optimization is the root of all evil</em>.</li>
<li>Services evolve continuously. Whether it means a new parameter in a remote procedure or a new field in a resource representation, it doesn’t matter much. And the <a target="_blank" href="https://blog.apisyouwonthate.com/api-versioning-has-no-right-way-f3c75457c0b7#API%20Evolution">API Evolution</a> concept is, as far as I’ve read, nothing but plain old wisdom from software development: don’t make breaking changes until absolutely needed, and use compatibility layers to help everyone move forward at a sane pace.</li>
<li>Even if you design your API awkwardly, it will certainly be dead loooong before it has real compatibility issues. Maybe not because its purpose has become irrelevant, and maybe not because of crushing competitors, but likely because of changes-of-mind in your marketing department.</li>
<li>With the time spent to properly integrate most REST-style APIs, one could implement several successive versions of corresponding lightweight RPC webservices. Let’s remain pragmatic.</li>
<li>When a tech startup, with a life expectancy below 2 years, spends one third of its time writing REST(ish) boilerplate, its CTO might deserve to be slapped with a large trout. Good programming practices and cheap workarounds are all they need, until they reach the state where scalability becomes a matter worth thinking about and spending money on.</li>
</ul>
<p>Most importantly, please give up this Holy Grail Quest called “HATEOAS,” unless you’re part of the few Knights in the world concerned by this Mission.</p>
<p>REST/HATEOS is for specific data-centric APIs: those which are naturally CRUD, those which are consumed via ActiveRecord or DataMapper patterns in your favorite languages, those which do not have tons of subtle constraints and side-effects between the fields of a model, and those meant to be explored by humans (currently the only entities in the universe able to understand what this newly appeared “<em>billing contact email</em>” field means).</p>
<p>Otherwise, you’ll end up with the awkwardness of RESTish APIs, but with an extra stack of complications.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/3hlZJG4kPDdGKmn7yyoOFW-Yq8V4AIVsueyM" alt="Image" width="640" height="354" loading="lazy">
<em>When used inadequately, REST is like “Monty Python and the Holy Grail,” but with thousands of rabbits</em></p>
<p>One relevant use case for HATEOS would be a generic “Database Admin Protocol,” allowing any server to drive a same generic Single Page Application through the structure of its (SQL or no-SQL) database: navigation between tables and record pages, autogenerated forms for each schema, dynamic create/edit/delete buttons, and so on.</p>
<p>In similar fashion, an API dedicated to browsing and editing documentation, or exploring/pulling/pushing a Version Control System, would lend itself well to a REST architectural style. But these are far, very far, from what most webservices are built for. And if <a target="_blank" href="https://githubengineering.com/the-github-graphql-api/">Github switched from REST to GraphQL</a> for its API, it’s a hint that the benefits claimed by REST were just <em>not enough</em>.</p>
<h3 id="heading-where-did-it-go-wrong"><strong>Where did it go wrong?</strong></h3>
<p>So here we are. REST/HATEOS is certainly a nicely evolved architectural style, but (imho) only relevant to a tiny fraction of use cases. And now it has spread like cancer over the ecosystem of webservices — mostly under its truncated form called “RESTish APIs” — bringing inadequacy and artificial complexity everywhere.  </p>
<p>Who is to blame for this awkward situation?</p>
<ul>
<li>The original dissertation, which didn’t position REST in comparison to other architectures, and remained too vague on its pros and cons?</li>
<li>The REST advocates, who often lost themselves in very subjective (when not contradicting) recommendations, instead of advertising standards and explaining when (not) to use REST?</li>
<li>The uncountable articles who displayed a false dilemma between SOAP and REST, thus propelling to the stars a winner by default?</li>
<li>The Internet trolls who proclaimed, in about every StackOverflow thread regarding webservices design, “<em>Forget existing protocol XYZ, it’s an extra layer which makes stuffs unmaintainable, all you need is handmade HTTP</em>”?</li>
<li>The buzzword lovers who imposed REST to their teams, without discussing the impacts of this architectural change, without ever asking themselves “<em>but why though?</em>”</li>
<li>The silent mass of developers, who, like me, have known FOR YEARS that something was deeply wrong, but haven’t blown the whistle?</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/N42-nijzWSHyLEQCHFSL7nNNQops1B0Qhj2Y" alt="Image" width="700" height="495" loading="lazy"></p>
<p>Yup. I guess it’s a mix of all these.</p>
<p>The cruel irony of this story is that the <a target="_blank" href="https://www.ics.uci.edu/~fielding/pubs/dissertation/introduction.htm">original dissertation</a> itself warned about bandwagon jumping and improper architectural choices:</p>
<blockquote>
<p>“H<em>ow often we see software projects begin with adoption of the latest fad in architectural design, and only later discover whether or not the system requirements call for such an architecture. Design-by-buzzword is a common occurrence. […] The REST interface is designed to be efficient for large-grain hypermedia data transfer, optimizing for the common case of the Web, but resulting in an interface that is not optimal for other forms of architectural interaction.</em>”</p>
</blockquote>
<p>Some good news, however, is that REST has paved the way for other protocols, like GraphQL and HTTP2. And its use of advanced HTTP features is an inspiration for other architectures. We owe it at least that.</p>
<h3 id="heading-what-if-you-really-have-to-restify">What if you <em>really</em> have to RESTify?</h3>
<p>For lots of reasons (like corporate hierarchy, or really needing CRUD with HTTP caching), you might have to go for REST. With or without HATEOAS.</p>
<p>In my previous article, I suggested that industrializing REST clients and servers was a problem without solution. <strong>It turns out I was wrong</strong><em>.</em></p>
<p>Here is an non-exhaustive list of REST-related “standards”, grabbed from the inputs of various commenters. You can find a lot more on Phil Sturgeon’s new <a target="_blank" href="http://standards.rest/">standards.rest</a> listing.</p>
<ul>
<li>To specify semantics of PATCH: JSON Patch, JSON Merge Patch</li>
<li>To specify interface contracts: JSON Schema, API Blueprint, OpenAPI (formerly Swagger), RAML, GraphQL Types, XML Schema</li>
<li>To serialize results and/or errors in responses: JSend format, RFC7807 (Problem Details for HTTP APIs), Sparse fieldsets (restricting the fields to return), Compound documents (including related resources)</li>
<li>Protocols with hypermedia controls: JSON Hyper-Schema (IETF Draft), JSON Hypertext Application Language or “HAL” (IETF Draft), Json-API, OData, Mason, Hydra/JSON-LD, JSON SIREN</li>
</ul>
<p>These are indeed quite a good number of possibilities. A combinatorial explosion of possibilities, since many of them only take care of a small portion of the protocol. These efforts at standardizing are welcome, although they are somehow late: the most RESTful ones (for hypermedia) are, nearly 18 years after Roy Fielding’s dissertation, still drafts.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/i6CBAPMfBiy4qOpl5ceeYOwH3Y8EwOuBz8bc" alt="Image" width="650" height="488" loading="lazy">
<em>REST APIs have standards. Like phone chargers do.</em></p>
<p><strong>Do you know why I didn’t cite any of them in my previous rant?</strong></p>
<p>Because during all those years spent integrating the APIs of big companies (think Google, Microsoft, Oracle, Dropbox, Spotify, and others), as well as that of smaller enterprise, <strong>NOT ONCE</strong> have I met any of these “standards”, neither explicitly nor implicitly. Maybe it’s because I was unlucky. Maybe it’s because they are rarely used.</p>
<p>From my point of view, this lack of visible standardization has to do with the <strong>original sin of the REST</strong>: for some reason, it came with a very strong anti-standards mindset, with an obscurantist “<em>all you need is love and HTTP</em>” philosophy. So even the most talented developers felt the urge to specify their own half-baked protocol, in their corner, oblivious to thousands of others who had already done the same.</p>
<p>In your case, naturally, the least harm will be to use existing standards and libraries. Preferably <strong>full-fledged protocols</strong>, rather than LEGO-style assemblies of RFCs.</p>
<p><strong>I shall warn you, though. Here be dragons, too.</strong></p>
<p>Sometimes, the devil is in the details. An old wisdom in computer sciences states that errors shall not go silent. That’s why it’s good practice to keep the format of objects consistent: some of their fields might be nullified, but they are present at all time anyway (unless asked otherwise by the client). That’s the best way to prevent <em>false negatives</em> (due to typos), and to avoid random breakages in strict clients if the <em>quantic</em> property of these fields was (as often) not properly documented.</p>
<p>I thought that this idea naturally applied to REST representations, too. Too bad: standards like <a target="_blank" href="https://tools.ietf.org/html/rfc7386">JSON Merge Patch</a> force you to delete remote fields instead of nullifying them. These tiny but apocalypse-triggering details are especially inappropriate in a philosophy which claims to “<em>help client and server evolve independently.</em>”</p>
<p>Sometimes, the devil is elephant-sized. Ever heard about this OpenAPI (formerly Swagger), one of the most ambitious REST standards? The idea is to describe your API in a specification file, with endpoints and schemas, and use OpenAPI tools to industrialize the creation of both client and server. It sounds nice, doesn’t it?</p>
<p>Here is an <a target="_blank" href="https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json">example json interface spec</a>, for the Kubernetes API. Yes, Json schemas are by nature extremely verbose.</p>
<p>Ok, now here is the <a target="_blank" href="https://github.com/kubernetes-incubator/client-python/tree/master/kubernetes/client">corresponding client implementation</a> for Python.</p>
<p>As of today, it’s more than 90,000 lines of Python code and comments, automatically generated by OpenAPI. Not just thin wrappers, to benefit from auto-documentation tools and IDE autocompletion. 90,000 lines. More than their json interface spec. What. the. actual. heck.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/WO3MynM9YLRWzKSWHvSWxHhVRoaYJCwCkjzZ" alt="Image" width="735" height="465" loading="lazy">
<em>When you ask OpenAPI for a catamaran</em></p>
<p>Each language, each framework, has its own idea on how to handle OpenAPI. Some choose <a target="_blank" href="http://radar.oreilly.com/2015/09/building-apis-with-swagger.html">hybrid (and elegantly cruft-free) approaches</a>. Some generate a spec file from server code. Most generate tons of boilerplate from said spec file. Sometimes they go farther and generate tests, too.</p>
<p>More tooling and more code generators mean more bugs and harder learning curves… and all that for what? The Kubernetes SDK is exposed to Python as a <a target="_blank" href="https://github.com/kubernetes-client/python/blob/master/kubernetes/README.md#documentation-for-api-endpoints">set of methods</a>. With hardcoded URLs. Again, some RPC-over-CRUD system, considered by many as state-of-the-art RESTfulness, while disregarding HATEOAS. I find all this utterly confusing, and I hope I’m not the only one.</p>
<p>So be especially wary about REST-related protocols and frameworks you might choose. Some are handy and efficient, but some make REST look more and more like the new SOAP.</p>
<h3 id="heading-tldr">TL;DR</h3>
<p>The original REST™ is like rocket engineering: exciting, but very specific, quite complex, and rather harmful unless you precisely know what you’re doing.</p>
<p>RESTish APIs are more affordable, but be sure that you‘ll benefit from them, since it’s rarely the case. To quote a simple rule of thumb from Phil Sturgeon:</p>
<blockquote>
<p>“<em>If an API is mostly actions, maybe it should be RPC. If an API is mostly CRUD and is manipulating related data, maybe it should be REST</em>”.</p>
</blockquote>
<p>Lots of REST(ish) “standards” exist, so no need to ever specify one from scratch. But whatever your needs are, beware of buzzwords, use the right tool for the right job (REST and RPC are only two amongst hundreds), and most importantly, <a target="_blank" href="https://en.wikipedia.org/wiki/KISS_principle">KISS</a>. I bet you’d have more success using a generic JsonAPI client and validating it against a real preprod server, than spending days generating tons of boilerplate OpenAPI code — only to discover later that it doesn’t actually match the remote side because of bugs or other incompatibilities.</p>
<p>The same goes for other architectures, by the way: you’ll probably save time using simple JsonRPC or JsonWSP protocols, instead of generating boilerplate with gRPC, only to later realize that this shiny protocol hasn’t even specified how to report application-level errors.</p>
<h3 id="heading-epilogue">Epilogue</h3>
<p>REST is a difficult subject to talk about. There are lots of plot holes in the founding dissertation, lots of conflicting definitions, lots of contradicting opinions on how to do this or that right, lots of unjustified hypes and disgraces, lots of (underused and partial) standards… and very few real life examples of HATEOAS APIs (most links I’ve crossed were dead, so much for the “<em>lasting decades</em>”).</p>
<p>But I hope that this analysis has clarified a bit the different “RESTs” people are talking about, and that it will spare you some of the obscene amount of time I had to spend just to somehow understand what the Original REST™ was meant to be.</p>
<p>At the very least, you now have a new weapon in your bag. The next time your boss wants you to expose some server operations as REST webservices, just ask:</p>
<p><strong>For this API, do we really need to follow a composite architectural style meant for Internet-scale distributed hypermedia systems?</strong></p>
<p>The expression on his face will be your answer.</p>
<p><strong>Please leave your comments below. And here are past comments about this article on Medium: <a target="_blank" href="https://medium.com/p/21c59d243438/responses/show">https://medium.com/p/21c59d243438/responses/show</a></strong></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
