<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jeremy Wells on Medium]]></title>
        <description><![CDATA[Stories by Jeremy Wells on Medium]]></description>
        <link>https://medium.com/@jeremywellsio?source=rss-96da70f12595------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DDWa06v2XT1hyp8Fc5sMjg.jpeg</url>
            <title>Stories by Jeremy Wells on Medium</title>
            <link>https://medium.com/@jeremywellsio?source=rss-96da70f12595------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:05:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeremywellsio/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Show and tell: my Eleventy plugin]]></title>
            <link>https://jeremywellsio.medium.com/show-and-tell-my-eleventy-plugin-f67aebfdc36c?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/f67aebfdc36c</guid>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 15:16:08 GMT</pubDate>
            <atom:updated>2023-08-09T15:16:08.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*fAmxjTvuXOqk-6AL.jpg" /></figure><p>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Winkler</a> on <a href="https://unsplash.com/photos/9QTFMkh-ezM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p><p>This year, I’ve become a pretty big fan of a newer-ish static site generator called <a href="https://www.11ty.dev/">Eleventy</a>. After playing around a bit, I took on the project converting this site to an Eleventy-generated blog. Eleventy has got a pretty rich API, and I found that three configuration methods it provides — filter, addShortcode, and addPlugin - lend themselves really well to extending the tool&#39;s functionality. This post is to document the process for creating a little Eleventy plugin of my own (<a href="https://www.npmjs.com/package/eleventy-gist">Eleventy Gist</a>) by iterating through the different levels of abstraction that can be attained through the Eleventy API.</p><h3>V2-ing my little tech blog</h3><p>After a busy year, I decided to dust off this blog to see if I could get back to some regular tech writing. One thing that snuck up on me in the intervening year was my <a href="https://jekyllrb.com/">Jekyll</a> setup had broken. I’d need to go down some rabbit holes between getting a Ruby environment reconfigured and figuring out what Gem updates needed sorting out. And not being a Ruby developer, it wouldn’t have been the most useful learning experience.</p><p>Instead, I looked at a few of the newer static site generators in town and happened upon <a href="https://www.11ty.dev/">Eleventy</a>. After going through a couple of basic tutorials, I found a lot to like: it’s simple but versatile, it’s easy to configure, it generates the site quickly, and best of all it’s Javascript all the way down, which is much more in my wheelhouse. There were a few tutorials out there that got me around a few of the well known obstacles when it comes to porting Jekyll sites to Eleventy. Generally, I was able to copy over my old posts without having to modify the files too much — and I really don’t have enough posts to necessitate much automation anyway.</p><p>But one big obstacle in porting the site was a Jekyll plugin called <a href="https://www.jeremywells.io/posts/2023-08-01-11ty-gist/">jekyll-gist</a> that I had made use of for including code snippets. It basically takes the contents of a <a href="https://gist.github.com/">Github Gist</a> file and outputs it inside of a &lt;code&gt;&lt;/code&gt; block on the page. As far as I could tell, it has no equivalent in the Eleventy-verse. And going into each post, finding each reference to the Jekyll Gist plugin, hunting down the gist, then manually pasting the contents just did not sound like an afternoon well spent. Plus, I&#39;d still like to use Github Gists in my workflow. Here was an opportunity to go a little deeper into Eleventy and build <a href="https://www.npmjs.com/package/eleventy-gist">my first Eleventy plugin</a>.</p><p>I came up with the following basic requirements for the plugin:</p><ul><li>I can output the contents of a Github Gist to a static web page.</li><li>I can add this functionality to an Eleventy-generated site with a plugin.</li><li>I can configure this plugin to use a Github bearer token.</li><li>I can use a similar syntax in my templates as the Jekyll Gist plugin.</li><li>I can make this plugin available via npm.</li></ul><h3>Iterating with Eleventy’s configuration methods.</h3><p>After a few false starts, one aspect of Eleventy that helped with iterating over the logic I wanted to implement was the different configuration methods available in the tool, which offer different levels of abstraction.</p><ol><li>A <a href="https://www.11ty.dev/docs/filters/">Filter</a> can be used to transform a value and output it to the generated page.</li><li>A <a href="https://www.11ty.dev/docs/shortcodes/">Shortcode</a> is like a method that extends the syntax of the template language you’re using.</li><li>A <a href="https://www.11ty.dev/docs/plugins/">Plugin</a> is a separate, reusable module that can be imported into an Eleventy config.</li></ol><p>So when developing and testing this new functionality, iterating through the different configuration methods could look something like this:</p><h3>1. Use a filter to validate the content that gets output to the page</h3><p>I created a dummy post file ($ touch content/posts/gist-testpost.md). I set up the Github API to return a Gist from an old post and copied the content string, then passed that to a variable in the dummy post:</p><pre>{% set myGist = &#39;// javascript export function doTheThing(myArg) { console.log(&quot;doin the thing&quot;);}&#39; %}</pre><p>Then, I sent that to a yet-unimplemented filter:</p><pre>{{ myGist | gist }}</pre><p>And as expected, on rebuilding the site, errors and chaos ensue.</p><p>Then, to implement and test how the raw file content gets rendered onto the page, I created the filter in the eleventy.config.js:</p><pre>module.exports = function (eleventyConfig) {<br>    // ...<br>    eleventyConfig.addFilter(&#39;gist&#39;, content =&gt; {<br>        const ext = &#39;js&#39;;<br>		return &#39;```&#39; + ext + &#39;\n&#39; + content + &#39;\n```&#39;;<br>	});<br>    // ...<br>}</pre><p>And with that, I was able to work out how the content of one gist would look in my site, adjusting the syntax highlighting and styling as needed.</p><h3>2. Use a shortcode to test the feature as a standalone module</h3><p>After seeing basically how the output of a gist would render in the site, it was time to develop the eleventy-gist module itself. I created a temporary plugin directory to store the files ($ mkdir -d plugins/gist) and some files ($ touch plugins/gist/{gist.js,gist.test.js,requestWrapper.js}), and I was able to use tests with <a href="https://www.jeremywells.io/posts/2023-08-01-11ty-gist/">Jest</a> to work out the gist function.</p><p>One extra file that was necessary was requestWrapper.js that isn&#39;t much more than an HTTP request body using the native Node.js https module:</p><pre>const https = require(&#39;https&#39;);</pre><pre>module.exports = async function request(options) {<br>    return new Promise((resolve, reject) =&gt; {<br>        const req = https.request(options, res =&gt; {<br>            if (res.statusCode &lt; 200 || res.statusCode &gt;= 300) {<br>                return reject(new Error(&#39;API error: statusCode = &#39; + res.statusCode));<br>            }<br>            let body = [];<br>            res.on(&#39;data&#39;, d =&gt; body.push(d));<br>            res.on(&#39;end&#39;, () =&gt; {<br>                body = JSON.parse(Buffer.concat(body).toString());<br>                resolve(body);<br>            })<br>        });<br>        req.on(&#39;error&#39;, e =&gt; reject(e.message));<br>        req.end();<br>    });<br>}</pre><p>This helps remove real requests to the Github API from the unit tests, and we can mock it in Jest like this:</p><pre>jest.mock(&#39;./requestWrapper&#39;);<br>const request = require(&#39;./requestWrapper&#39;);</pre><pre>const createAPIResponse = (fileName, contentText) =&gt;<br>    ((copyFileName, copyContentText) =&gt; {<br>        let fileName = copyFileName;<br>        let contentText = copyContentText;<br>        return {<br>            getResponse() {<br>                return {<br>                    files: { [fileName]: { content: contentText } }<br>                };<br>            },<br>            addFileToResponse(fileName, contentText) {<br>                const response = this.getResponse();<br>                response.files[fileName] = { content: contentText };<br>                return response;<br>            }<br>        }<br>    })(fileName, contentText);</pre><pre>const createOpts = () =&gt; {<br>    return { authToken: &#39;12345&#39;, userAgent: &#39;dave grohl&#39; };<br>};</pre><p>Then using the mock in a test looks something like this:</p><pre>describe(&#39;gist() : &#39;, () =&gt; {<br>    test(&#39;if called w/o authToken or userAgent does not call github API&#39;, async () =&gt; {<br>        const testObj = createAPIResponse(&#39;01.sh&#39;, &#39; echo hello &gt; myfile.txt &#39;).getResponse();<br>        request.mockResolvedValue(testObj);<br>        const opts = null;<br>        const result = await gist(&#39;&#39;, &#39;&#39;, opts);<br>        expect(request).not.toHaveBeenCalled();<br>        expect(result).toBe(&#39;&#39;);<br>    });<br>});</pre><p>From there, I can test and develop the gist() function:</p><pre>async function gist(gistId, fileName, opts) {<br>   // ...<br>    try {<br>        verifyOptions(opts);<br>        const result = await run(gistId, fileName, opts);<br>        return result;<br>    }<br>    catch (e) {<br>        // ...<br>        console.log(errorMessage);<br>        // ...<br>        return &#39;&#39;;<br>    }<br>}</pre><pre>module.exports = { gist };</pre><p>You can see <a href="https://github.com/jsheridanwells/eleventy-gist/tree/main">the final repo</a> for the full implementation.</p><p>Finally, using an Eleventy <a href="https://www.11ty.dev/docs/shortcodes/">shortcode</a>, I can import and test the gist() function for real:</p><pre>const gist = require(&#39;./plugins/gist/gist/&#39;)</pre><pre>const config = {<br>    // ...(I&#39;ll talk about the config a little later)...<br>};<br>module.exports = function (eleventyConfig) {<br>    // ...<br>    eleventyConfig.addShortcode(&#39;gist&#39;, async function (gistId, fileName) {<br>        return gist(gistId, fileName, config);<br>    });<br>    // ...<br>}</pre><p>Cool. So through a combination of Test-Driven Development, then using a shortcode to see how the gist() function worked in the real site, I was able to find and work out a few issues:</p><ul><li>I needed a configuration object to store things like a bearer token for the Github API, as well as a user name to pass to the User-Agent HTTP header.</li><li>When I ran the live development server that comes with Eleventy, on every save, gist() would call the Github API for every single use of the {% gist %} shortcode. I noticed this dramatically increased the build times. I needed <a href="https://github.com/jsheridanwells/eleventy-gist/blob/main/cache.js">a way to cache the results</a> the first time the contents loaded, especially if the site was in development mode.</li><li>The Github API of course sends back errors as APIs will do. I needed a way to communicate that in the console.</li><li>Also, if the user adds the ID or a file name of a gist that doesn’t exist, when in development, it would be helpful to see it really clearly on the page. I added a debug option to the configuration that will output a big red message on the page so it&#39;s at least a little easier to spot. Otherwise, in production errors will return an empty string to hide the issue from the public.</li></ul><p>So, when hooked up to <a href="https://www.npmjs.com/package/dotenv">dotenv</a> for reading environmental variables, a sample eleventy.config.js will look like this:</p><pre>require(&#39;dotenv&#39;).config();<br>const gist = require(&#39;./plugins/gist/gist/&#39;)<br>const config = {<br>    authToken: process.env.github_access_token,<br>		userAgent: process.env.github_user_agent,<br>		debug: process.env.NODE_ENV === &#39;development&#39;,<br>		useCache: process.env.NODE_ENV === &#39;development&#39;<br>};</pre><pre>module.exports = function (eleventyConfig) {<br>    // ...<br>    eleventyConfig.addShortcode(&#39;gist&#39;, async function (gistId, fileName) {<br>        return gist(gistId, fileName, config);<br>	  });<br>    // ...<br>}</pre><p>With a .env file set up something like this (don&#39;t forget to list it in your .gitignore):</p><pre>NODE_ENV=&quot;development&quot;<br>github_access_token=&quot;YOUR SECRET TOKEN&quot;<br>github_user_agent=&quot;@YOUR USER NAME&quot;</pre><h3>3. Use an Eleventy plugin to test the feature as an NPM package</h3><p>The last step was to move my gist files to their own directory and set them up as an NPM package. Then, in the Eleventy config, I could call the function with addPlugin instead of addShortcode. Once this worked as expected, Eleventy would be all set to install and use the gist() function as a third-party package.</p><p>Before doing any of that, let’s point out what an Eleventy plugin does differently. When our plugin is fully converted, adding it to the Eleventy config will look like this:</p><pre>const config = {<br>    // ...same config...<br>};<br>module.exports = function (eleventyConfig) {<br>    // ...<br>    eleventyConfig.addPlugin(gist, config);<br>}</pre><p>Basically, any of the logic from the body of the addShortcode callback method will be abstracted away to the plugin. Plugins in Eleventy work by taking the context of the configuration and doing all the work in the plugin rather than in the consuming application.</p><p>Back in the plugin project, I needed to export the gist() function within an anonymous function that takes the Eleventy configuration context as it&#39;s first argument, then whatever else is needed from the Eleventy config. I added an index.js file to the eleventy-gist project that looks like this:</p><pre>const { gist } = require(&#39;./gist&#39;);</pre><pre>module.exports = async function(config, opts = {}) {<br>	config.addShortcode(&#39;gist&#39;, async function (gistId, fileName) {<br>        return gist(gistId, fileName, opts);<br>  });<br>}</pre><p>We can see here that the function receives the Eleventy config object (here it’s generically called config), then everything in the addShortcode from above is moved into here.</p><p>Now back in the eleventy.config.js, I replaced the addShortcode method with addPlugin:</p><pre>const config = {<br>    // ...same config...<br>};<br>module.exports = function (eleventyConfig) {<br>    // ...<br>    eleventyConfig.addPlugin(gist, config);<br>}</pre><p>Now that the gist function is a plugin, it can just be added and configured in eleventy.config.js, and all the other details are abstracted away. Once this change was working, it was time to move the new files to their own NPM project.</p><p>The following steps were the standard way of creating an NPM package, so I won’t go into too much detail.</p><ol><li>Move the files from the plugins directory in the Eleventy project, to their own project (/eleventy-gist in my case).</li><li>Initialize the project ($ npm init) and add any required npm modules (I only needed Jest: npm install --save-dev jest).</li><li>Back in the eleventy project, add eleventy-gist to the package.json and reference the local path (for some final tests before publishing):</li></ol><pre>{<br>  &quot;...&quot;: &quot;...&quot;,  <br>  &quot;devDependencies&quot;: {<br>    &quot;eleventy-gist&quot;: &quot;../eleventy-gist&quot;,<br>    &quot;...&quot;: &quot;...&quot;<br>  }<br>}</pre><ol><li>Adjust the import in the eleventy.config.js accordingly, then give it a test. However it works here should be exactly how it will work when imported via $ npm install ....</li><li>If everything is good, create your npm project, or repo, or whatever you need to distribute your project, then npm publish.</li><li>Update the package.json in the Eleventy project to reference the package remotely and everything should be ready.</li></ol><p>And through the process of switching out different Eleventy configuration methods — filter for initial hard-coding and working out the expected output; addShortcode for working out the actual function through TDD; and addPlugin to convert the function to a separate project.</p><p>If <a href="https://github.com/jsheridanwells/eleventy-gist#readme">Eleventy Gist</a> might be something you could use, give it a go and <a href="https://github.com/jsheridanwells/eleventy-gist/issues">post and issue</a> if I can make it better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f67aebfdc36c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A headless Raspberry Pi workflow]]></title>
            <link>https://blog.devgenius.io/a-headless-raspberry-pi-workflow-90cd90596854?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/90cd90596854</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 17:33:09 GMT</pubDate>
            <atom:updated>2022-01-23T16:29:20.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*amGrpR0eygvBJ5ya.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@0leil"><strong>Quentin Schulz</strong></a> on <a href="https://unsplash.com/photos/51nYPDEafWc"><strong>Unsplash</strong></a></figcaption></figure><p>It’s always great to follow-up on a cool hobby IOT experiment, and I’ve collected a few Ardunios, Trinkets, and Raspberry Pis that are always waiting around for a free weekend. The Raspberry Pi can be a wonderfully versatile little computer that exposes pins for external controllers and sensors, but it could also be a simple $35 home server, or even a fully functioning Linux desktop computer.</p><p>My kids and I have set up our own Minecraft server, and I’ve made a little weather clock, and experimented with server deployment configurations and a home media streamer as well. Some more elaborate projects I’d like to try some day include a <a href="https://ubuntu.com/tutorials/how-to-kubernetes-cluster-on-raspberry-pi#1-overview">Raspberry Pi Kubernetes cluster</a> or a <a href="https://www.gratefuldeadtimemachine.com/build-your-own">Grateful Dead Time Machine</a>. Since the whole OS lives on a Micro SD card, it’s easy to keep a few and flash different OSes, swapping them out for different projects. In fact, with all of the intricate AWS and Azure learning I’ve had to do for my job, using a Raspberry Pi to test out provisioning a bare-bones server is a great way to step back and get a handle on what’s actually happening under the hood when you’re sending your artifacts off to some nebulous data center with a simple command.</p><p>One set of steps I always find myself looking up and repeating is for creating a Headless Raspberry Pi — just configure an OS on an SD card and turn it on, no keyboard, no monitor, just the machine.</p><p>You can certainly load a Raspberry Pi with its custom OS, a Linux Debian port called Raspbian, hook it up like a desktop computer and do all of the above. But for me, the most convenient way is to set it up on my local WiFi network and connect to it from the workstation where I do everything else, using my personal dev environment and code editors to also load programs onto the Raspberry Pi. That’s where a headless, no-GUI Raspberry Pi is ideal.</p><p>In this article, I’ve combined steps from the tutorials I usually reference so that I’ve got some quick, easy steps to follow every time I put together a new headless Raspberry Pi from scratch.</p><h3>Prereqisites</h3><p>For this article, the only thing you’ll need is a Raspberry Pi, the model doesn’t matter. In fact, most of these steps are more related to provisioning a simple Linux server, so they could be applicable to several other hardware as well. You’ll also need some sort of SD card reader on your desktop computer.</p><h3>Creating your Raspberry Pi image</h3><p>The first, quickesy way to set up a Raspberry Pi OS is using the <a href="https://www.raspberrypi.com/software/">Raspberry Pi Imager</a>.</p><ul><li><a href="https://www.raspberrypi.com/software/">Download a copy</a></li><li>Meanwhile, plug in an SD card to whatever SD card reader you have.</li><li>You may want to re-format the SD card so that the OS image is freshly installed. On a Windows computer, I do this by finding the SD card drive in File Explorer under “This PC” and right-clicking it for its formatting options. Choose “FAT” as the file system type, and the default selections for everything else. Note, that any data already on the card will be erased.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*40GX5DZbIG_oua8n.png" /></figure><ul><li>Once the Raspberry Pi Imager is done downloading, open it up. You may have to give it administrative permissions on your computer.</li><li>You’ll have two selections to make, <strong>1. Choose OS</strong> and <strong>2. Choose Storage</strong>.</li><li>Click “Choose OS” and select Raspberry Pi OS (Other), then Raspberry Pi OS Lite (32-bit). This version of the OS doesn’t include a Desktop environment so it will only be controllable from the terminal.</li><li>Click “Choose Storage” and one of the options should be the drive for the SD card that you formatted earlier.</li><li>Lastly, click the “Write” button and the imager will do its work to load a boot-able OS onto the SD card. On my machine, this process takes about 5 minutes.</li></ul><h3>SSH and networking config</h3><p>After the imaging is complete, you could eject the SD card and boot up the Raspberry Pi with a monitor, then see a Linux command-line interface. But since this is going to be a headless, peripheral-free setup we need to give the OS some extra information to enable it to connect to a local WiFi network and enable to us to connect it to it from a workstation.</p><p>If the SD card drive was ejected after the image was written, plug it back in and open it in File Explorer or Finder:</p><ul><li>Add an empty file called ssh in the top directory of the SD card. The file shouldn’t have an extension, or any content inside. This tells the OS to accept SSH connections when it boots.</li><li>With a text editor create a file called wpa_supplicant.conf. This is where you’ll add information so it can connect to your local WiFi network on startup. Paste the following text, substituting your own Wifi name and password:</li></ul><pre>country=US<br>ctrl_interface=DIR=/var/run/wpa_supplicat GROUP=netdev<br>update_config=1<br><br>network={<br>	ssid=&quot;&lt;YOUR WIFI NAME&gt;&quot;<br>	scan_ssid=1<br>	psk=&quot;&lt;YOUR WIFI PASSWORD&gt;&quot;<br>	key_mgmt=WPA-PSK<br>}</pre><ul><li>Also save this file on the SD card in the root directory.</li></ul><h3>First Login</h3><p>Your Raspberry Pi OS should be good to go. Plug the card into the Raspberry Pi and turn it on. It should only take a minute or two to boot up. Once it does, open a termninal on your workstation computer and make an SSH connection using the default login:</p><pre>$ ssh pi@raspberrypi.local</pre><p>The password will be raspberry. If you are successful, you’ll see the command-line interface for the Raspberry Pi and you’re ready to run commands.</p><p>The set of the commands in the terminal will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*RkImKUSurrlUb3_K.png" /></figure><p>The first thing I do is change the hostname. That way, if I run multiple Raspberry Pis on the same local Wifi, there’s no confusion.</p><ul><li>In the Raspberry Pi terminal, type $sudo raspi-config. This will bring up the configuration options.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/0*hBu_j0CYMzJHEKPp.png" /></figure><ul><li>Select 1 System Options</li><li>Select S4 Hostname and you’ll be prompted to change the hostname. Now, when you SSH into the machine, it will be ssh pi@&lt;NEW HOSTNAME&gt;.local</li><li>Exit the config screen and you can reboot if you’d like.</li></ul><p>The next thing is to at the very least, change the password for the pi user. I like to replace the pi user with a brand new admin user. These are just regular Linux commands.</p><ul><li>Change the password for pi just to be safe. Type $ passwd and follow the prompts.</li><li>Create a new user: $ sudo add user &lt;USERNAME&gt;. It will prompt you for a password and ask for some user profile information.</li><li>Then add your new user to the sudo group so that they can run adminstrative commands:</li></ul><pre>$ sudo usermod -aG sudo &lt;USERNAME&gt;</pre><ul><li>You can switch to your new user: $ su - &lt;USERNAME&gt;</li><li>Or you can exit and reconnect with your new user:</li></ul><p>$ sudo reboot<br> $ ssh &lt;USERNAME&gt;@&lt;NEW HOSTNAME&gt;.local</p><ul><li>Once your reconnected, you can optionally remove default the pi user.</li></ul><pre>sudo deluser -remove-home pi</pre><ul><li>And to safely turn off the Raspberry Pi:</li></ul><pre>$ sudo shutdown now</pre><p>Now your Raspberry Pi is set up to run headlessly with and it’s at least minimally secure.</p><h3>Editing code directly on the Pi</h3><p>Now that you’re Raspberry Pi is provisioned, you’re ready to make it do some stuff. You’ll need to add some code to run. By default, it should have a working Python environment. But how do you get the code over to the Pi? You could fire up a bare-bones vim or nano editor, but that could be a little painful compared to the well-accessorized code editor on your local workstation.</p><p>One way to get around this is to set up your Raspberry Pi code as a remote Git repository, write the files in the local repository, then push them over. I used to do that, it’s not too complicated, and it you have the advantage of having a local repo to store all of your code and projects and have them last while you change out and reconfigure multiple Raspberry Pi setups. <a href="https://www.jeremywells.io/2022/01/10/headless-rpi.html">This article</a> gives some great instructions on how to go about setting up your own remote Git repository.</p><p>An even easier solution if you’re a VS Code user is, using a new plugin, you can access a directory on your Pi via SSH and edit files directly onto the Pi in your code editor.</p><p>In VS Code, install the plugin <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh">Remote — SSH</a>. Then type CTRL/CMD + SHIFT + P and type Remote - SSH Connect to Host. It will ask for an SSH url (exactly as above), prompt you for a password, then a new VS Code editor will open with access to the Raspberry Pi file system.</p><p>And with all that, you’ve got an unburdened Raspberri Pi for all your home tinkering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90cd90596854" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-headless-raspberry-pi-workflow-90cd90596854">A headless Raspberry Pi workflow</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing a Mongo Database]]></title>
            <link>https://medium.com/swlh/dockerizing-a-mongo-database-ac8f8219a019?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac8f8219a019</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 17:31:02 GMT</pubDate>
            <atom:updated>2021-02-22T20:39:52.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*bcNBzYNq9jZsSPsxrv7G8w.jpeg" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@sguruli?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Salomé Guruli</strong></a><strong> on </strong><a href="https://unsplash.com/s/photos/vines?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><h3>Introduction</h3><p>I tend to have about a dozen or so little tech projects loaded onto my machine at any given time — little web app ideas that I work on and stop, an occasional hackathon entry, something I’ve built working through a tutorial, a few experiments. I’ve gotten to really enjoy working with MongoDB over the past year, and I’ll usually add that in as a persistence layer when appropriate. One thing I’ve realized working off of a local MongoDB development server is all of those databases can accumulate, making it a little scary to experiment with different server configurations and deployment setups for one app. Indeed, one of the challenges during local development is constantly changing and reconfiguring the database as the project evolves, and safely dropping, rebuilding, and reseeding databases.</p><p>One way I’ve found to add some flexibility to the database layer when developing locally is using Docker to run a database server that’s dedicated to the project. By leveraging volumes with Docker, we can quickly configure, change, and migrate a database, making it easier to keep database configurations consistent in higher environments. Likewise, this setup can also simplify creating and tearing down pre-populated databases for automated tests.</p><p>In this article, I’ll show you my Docker setup for container configurations and scripts to run a project’s MongoDB server in a Docker container. We’ll add some configuration files for a local database, then go on to seed some data, as well as simple commands to tear down and rebuild the database.</p><h3>Prerequisites and loading the sample project</h3><p>In order to test out the Docker scripts, you’ll need <a href="https://www.docker.com/products/docker-desktop">Docker Desktop</a> running on your local development machine. If you want to follow along with the sample repo, you’ll also need <a href="https://nodejs.org/">Node.js</a> installed. Lastly, a database browser tool like <a href="https://www.mongodb.com/products/compass">MongoDB Compass</a> will be helpful for testing and inspecting the databases that we build.</p><p>To demonstrate, I’ve created <a href="https://github.com/jsheridanwells/MeanUrls">a simple MEAN-stack repo</a> and I’ll show how to add scripts for containerizing the database. However, you could also easily carry out these steps in any other project that uses Mongo — I’ll just be going over the Docker setup in this article. The example repo uses Angular, Express, and Typescript, but you don’t need to be familiar with any of those to follow along.</p><p>I won’t be explaining any MongoDB concepts, but that’s not likely to get in the way of understanding the steps below.</p><p>I’ll give a brief overview of some Docker terms and concepts so that the explanations are clear, but if you’re still getting started with Docker, <a href="https://docker-curriculum.com/">there are far better tutorials out there</a>.</p><p>Now for loading the sample project if you’re going to use it:</p><p>Clone the repo:</p><pre>$ git clone https://github.com/jsheridanwells/MeanUrls.git<br>$ cd MeanUrls</pre><p>The main branch of the repo is the complete example. There is also a branch called start which is the project without the setup. Check out the start branch and install the dependencies:</p><pre>$ git checkout start<br>$ npm install</pre><p>This example web app is an extremely simple URL shortener. There are a few npm scripts included to simplify running the project.</p><p>To compile and run the code for the API server:</p><pre>$ npm run cp:www<br>$ npm run build:api<br>$ npm run start:api</pre><p>You should see the Express app start up as expected, but then after a few seconds, an error will appear in the console because the application can’t connect to a database server. We’ll fix that below.</p><p>In a second terminal window, run the Angular client application:</p><pre>$ npm run start</pre><p>After the Node and Angular servers spin up, if you navigate to http://localhost:4200, you should see:</p><figure><img alt="A start page for the web application with a form, a button, and an empty results table" src="https://cdn-images-1.medium.com/max/654/0*tp-2LBby6wgV72hD.png" /></figure><p>Again, you’ll see some error messages in the browser console caused by not having a database available.</p><p>Stop both the API server and the Angular server (CTL+C).</p><h3>Some terms and concepts</h3><p>Before we set up our Docker configuration, I’d like to go over some concepts that will help clarify the steps we go through.</p><p><strong>Docker</strong> is a platform for creating virtual environments called <strong>containers</strong>. I think of a container as a tiny, isolated server that is given just enough resources to run a single, specific application or a task. Docker containers run on a <strong>host machine</strong> which is a physical piece of hardware, e.g. my computer if I’m developing locally, or the physical server in a public deployment. Docker containers come from <strong>images</strong> which are basically a blueprint for creating the container: at a minimum, an image will describe an operating system to run in the container, and it will usually also have packages and libraries installed to help an application accomplish a task.</p><p>One of the most powerful aspects of Docker is that we can layer different pre-configured images, then add our own configurations and artifacts. Hundreds of different vendors and platforms make official Docker images available for their products — different Linux flavors, different Windows products, MySQL, Postgres, SQL Server — and indeed it’s a great way to play with all sorts of different technologies. For our purposes, there is <a href="https://hub.docker.com/_/mongo">an official MongoDB image</a> that we’ll use to run a containerized database.</p><p>Once an image is defined, we can run the container on the host. When a container is run, usually we specify ports and network settings that are opened so that data can pass from the host machine to the container, or from container to container. We would also want to pass environment configuration settings to the container, for example a connection string so that the container can connect to an external database. Docker provides us with a variety of commands including one to run the container as a background process (<strong>“detached mode”</strong>), or with a command to be able to enter the container through the terminal and inspect its contents (docker exec, which we&#39;ll use later on).</p><p>One advantage of containers is that they are ephemeral — all you need is a command $ docker run &lt;...&gt; and the container will start with all of the components defined by its Docker image. When we don&#39;t need it, another command will make the container shut down and disappear. This helps developers to consistently deploy an application to different environments and to be sure it&#39;s most likely to run the exact same way. However, any data that is saved inside of the container will also disappear once the container is stopped. To handle persisted data, Docker uses <strong>volumes</strong> to connect data or files from the host machine to the container when it is running, as well as to write data from the container back to the host. There are two types: The first, <strong>bind mounts</strong> are directories that the developer manages directly. For example, if I want a directory of scripts available in the container, I can bind my local scripts directory in a project&#39;s source code to a directory in the container. The second type are called <strong>volumes</strong> and these are resources that are managed by Docker and live in a special location in the host machine&#39;s file system that we don&#39;t necessarily need to access directly. The advantage of using Docker volumes is that it gives us some special commands to create, manage, and dispose of persistent data that is consumed by a Docker container.</p><p>Lastly, <strong>Docker Compose</strong> is a feature that allows you to manage multiple Docker containers. Normally, it’s best practice for a Docker container to do only one thing, so for a web application, I might have one container to serve static files publicly, one container to handle the web API, and a third container to run a database server. Docker Compose allows us to create a YAML file, normally named docker-compose.yaml, to define how multiple containers are configured and how they are allowed to communicate with each other.</p><p>So, taking all of these concepts together, we are going to use Docker to run our development database server in the following ways:</p><ul><li>We’ll use the official MongoDB <strong>image</strong> to create a <strong>container</strong> to have all of the functionality of a Mongo server without having to go through the cumbersome process of installing it on a development machine.</li><li>We’ll <strong>bind mount</strong> a directory of startup scripts to a special directory on the Mongo container called /docker-entrypoint-initdb.d. Any bash scripts or Javascript files in this directory are immediately run when the container is launched. We&#39;ll use this to create a MongoDB database and an application user.</li><li>We’ll define a Docker <strong>volume</strong> so that the Mongo container can persist data on our host machine. If we ever need to remove all of the saved data and start over, we’ll have Docker commands available to do that.</li><li>Lastly, we’ll use <strong>Docker Compose</strong> to define the Mongo container as a service. With a docker-compose.yaml file defined, an application service or other services can be added on for a more robust application.</li></ul><p>For the rest of this article, I’ll go through the steps for accomplishing all of this.</p><h3>Environment variables</h3><p>The first thing to do is establish the various values we’ll need to build a MongoDB connection string and the names of the database and collection(s) for the project. The project contains the file env.sample with all of the values we&#39;ll need for this example:</p><pre>MONGO_INITDB_ROOT_USERNAME=mongo_root<br>MONGO_INITDB_ROOT_PASSWORD=mongo_root()<br>APP_USER=app_user<br>APP_PWD=app_user()<br>DB_NAME=MeanUrls<br>DB_COLLECTION_NAME=Urls<br>MONGO_HOSTNAME=mongodb<br>MONGO_PORT=28017</pre><p>These are the values that Docker will use to configure the server running in a Docker container. This example uses the following:</p><ul><li>The root login and password for the database server.</li><li>An app user and password. These are the credentials the application itself will use, This helps to limit the application’s access to just what it needs.</li><li>The name of the database and the name of a collection to start with.</li><li>The value MONGO_HOSTNAME is the name to access the database server in the Docker container from our host machine. This host name must match the name we give the container service that we&#39;ll set up later.</li><li>MONGO_PORT is the port that our application will use to access the database. MongoDB runs on port 27017 by convention; I like to change it to 28017 so I can tell it apart form any local instance of Mongo running on my machine, but that&#39;s just a personal preference.</li></ul><p>Adjust these variables if necessary, then copy them as your actual .env file.</p><pre>$ cp .env.sample .env</pre><p>This is the file that we’ll use to pass secret keys (e.g., the root password) to the Docker container and to the application. It can also be recreated for configuring secrets in a deployed application. As such, be careful not to check it into any version control.</p><p>If you look at the method buildMongoUrlin the file ./server/data/mongo.ts you can see where these values are used to build the Mongo connection string:</p><pre>public static buildMongoUrl(config: MongoDbConfig): string {<br>    return &#39;mongodb://&#39;<br>      + `${ config.appUser }:${ encodeURIComponent(config.appPassword) }`<br>      + `@${ config.hostName }:${ config.mongoPort }`<br>      + `/${ config.dbName }`;</pre><h3>Some setup scripts</h3><p>The official MongoDB image lets us start up the database using either a Javascript file or a Bash script. We’ll write some Javascript that will create the app user and the app database</p><p>We’ll create some directories to hold our Mongo scripts:</p><pre>$ mkdir -p ./scripts/mongo/init</pre><p>And a couple of files:</p><pre>$ touch ./scripts/mongo/init/{.dbshell,mongoInit.js}</pre><p>The .dbshell file is just a blank placeholder file that&#39;s used to create a Linux user to run the scripts in the container. mongoInit.js is where we&#39;ll create our user and database by pasting the following:</p><pre>// use shell command to save env variable to a temporary file, then return the contents.<br>// source: https://stackoverflow.com/questions/39444467/how-to-pass-environment-variable-to-mongo-script/60192758#60192758<br>function getEnvVariable(envVar, defaultValue) {<br>  var command = run(&quot;sh&quot;, &quot;-c&quot;, `printenv --null ${ envVar } &gt;/tmp/${ envVar }.txt`);<br>  // note: &#39;printenv --null&#39; prevents adding line break to value<br>  if (command != 0) return defaultValue;<br>  return cat(`/tmp/${ envVar }.txt`)<br>}</pre><pre>// create application user and collection<br>var dbUser = getEnvVariable(&#39;APP_USER&#39;, &#39;app_user&#39;);<br>var dbPwd = getEnvVariable(&#39;APP_PWD&#39;, &#39;app_user()&#39;);<br>var dbName = getEnvVariable(&#39;DB_NAME&#39;, &#39;MeanUrls&#39;);<br>var dbCollectionName = getEnvVariable(&#39;DB_COLLECTION_NAME&#39;, &#39;Urls&#39;);<br>db = db.getSiblingDB(dbName);<br>db.createUser({<br>  &#39;user&#39;: dbUser,<br>  &#39;pwd&#39;: dbPwd,<br>  &#39;roles&#39;: [<br>    {<br>      &#39;role&#39;: &#39;dbOwner&#39;,<br>      &#39;db&#39;: getEnvVariable(&#39;DB_NAME&#39;, &#39;MeanUrls&#39;)<br>    }<br>  ]<br>});</pre><pre>db.createCollection(dbCollectionName);</pre><p>The code in this script runs in the Mongo shell, so you’ll notice difference Mongo-specific objects are provided: e.g., db, run, cat.</p><p>The first function uses the mongo shell run command to retrieve environment variables (and I have to credit <a href="https://stackoverflow.com/questions/39444467/how-to-pass-environment-variable-to-mongo-script/60192758#60192758">this Stack Overflow hack</a> for help. Please let me know if there&#39;s a better way to do this).</p><p>Then, we create the database with db.getSiblingDB, a user with db.createUser, and a collection with db.createCollection.</p><p>Note that this script will only run when the container is initially started and bound to a Docker volume on the host, but not on any subsequent container startups bound to the same volume. This prevents any duplication or data collision when the container is shut down and restarted.</p><p>The next step is optional, but I want to also add some seed data so that I can test out the application right away. We’ll create a new directory:</p><pre>$ mkdir ./scripts/mongo/seed</pre><p>And we’ll download some data that I’ve already generated for the project using <a href="https://www.mockaroo.com/">Mockaroo</a>.</p><pre>$ curl https://raw.githubusercontent.com/jsheridanwells/MeanUrls/main/scripts/mongo/seed/MOCK_DATA.json -o ./scripts/mongo/seed/MOCK_DATA.json</pre><p>And we’ll create a bash script that will be available in the container to seed the database if we choose to:</p><pre>$ touch ./scripts/mongo/seed/mongo_seed.sh</pre><p>Add these contents to the file:</p><pre>#!/bin/bash<br>if [ -f &quot;/MOCK_DATA.json&quot; ]; then<br>  FILE=&quot;/MOCK_DATA.json&quot;<br>elif [ -f &quot;./MOCK_DATA.json&quot; ]; then<br>  FILE=&quot;./MOCK_DATA.json&quot;<br>else<br>  echo &quot;Mock data file not found. Make sure container has a MOCK_DATA.json file for this script to work&quot;<br>  exit 1<br>fi</pre><pre>mongoimport --host $MONGO_HOSTNAME \<br>  --authenticationDatabase $DB_NAME \<br>  --username $APP_USER --password $APP_PWD \<br>  --db $DB_NAME \<br>  --collection $DB_COLLECTION_NAME \<br>  --file $FILE --jsonArray</pre><p>This script checks for a MOCK_DATA.json file, and if found, runs the mongoimport command with the environment settings we created earlier.</p><h3>Creating our Mongo service</h3><p>We’ve got our keys for creating our database and app user, and scripts to tell Docker how to set them up when creating the container. Now we need to run it.j</p><p>Normally, a Docker container is configured with a Dockerfile that is responsible for selecting a base image, building and copying artifacts from the project&#39;s source code, running any special commands or configurations, and a lot more, then the result is a new Docker image.</p><p>In our case, we’re not changing any behaviors of the official MongoDB Docker image, or adding our own code, so we’ll run the MongoDB container as-is. We’ll use Docker Compose to configure and run the container as a service that’s then available to our application running on the host machine.</p><p>Docker Compose is configured using a YAML file, conventionally named docker-compose.yaml. Let&#39;s create one at the root of the project:</p><pre>$ touch ./docker-compose.yaml</pre><p>Now paste the following:</p><pre>version: &quot;3&quot;<br>services:<br>  mongodb:<br>    container_name: mean_urls_db<br>    image: mongo:latest<br>    volumes:<br>      - ./scripts/mongo/init/:/docker-entrypoint-initdb.d<br>      - ./scripts/mongo/init:/home/mongodb<br>      - ./scripts/mongo/seed/:/home/mongodb/seed<br>      - mean_urls_data:/data/db<br>    ports:<br>      - &quot;28017:27017&quot;<br>    environment:<br>      - MONGO_INITDB_ROOT_USERNAME=$MONGO_INITDB_ROOT_USERNAME<br>      - MONGO_INITDB_ROOT_PASSWORD=$MONGO_INITDB_ROOT_PASSWORD<br>      - APP_USER=$APP_USER<br>      - APP_PWD=$APP_PWD<br>      - DB_NAME=$DB_NAME<br>      - DB_COLLECTION_NAME=$DB_COLLECTION_NAME<br>      - MONGO_HOSTNAME=$MONGO_HOSTNAME<br>volumes:<br>  mean_urls_data:</pre><p>Here’s a walkthrough of what the yaml file is doing:</p><ul><li>version: &quot;3&quot; is the version of Docker Compose we&#39;re using, the latest as I write this.</li><li>We’ve named the service mongodb. This will become the host name of the MongoDB server and must match MONGO_HOSTNAME in the .env file.</li><li>We’ll build a container from the official MongoDB image: image: mongo:latest.</li><li>In the volumes list there are a few things going on: &gt; - First, note that for each item, the syntax is such that the value to the left of the colon (:), pertains to the host machine, while to the right belongs to the container (./host-directory:/container-directory). &gt; - We&#39;re mounting ./scripts/mongo/init to the directory on the container called /docker-entrypoint-initdb.d. As mentioned earlier, this is a special directory that runs any Javascript or Bash scripts inside of it when the container is first created. &gt; - We&#39;ll also mount init to /home/mongodb on the container. This creates the Linux user that can run the scripts with the Mongo shell. &gt; - The seed scripts will be copied over to /home/mongodb/seed. That way they&#39;re available to seed the database when the container is running if we want. &gt; - The last item - mean_urls_data:/data/db will bind the Mongo database files as a Docker volume. This allows data to persist when the container is stopped and restarted. It lets us easily wipe out all of the Mongo data and start over when necessary.</li><li>Moving on, in ports, we&#39;re connecting our local 28017 port to the conventional Mongo port 27017 on the container.</li><li>The environment list will set all of the environment variables from .env in the container.</li><li>Lastly, volumes: mean_urls_data creates and names the Docker volume on the host machine and must match the last item of the volumes list set when defining the mongodb service.</li></ul><h3>Getting it up and running</h3><p>It’s time to test out the database now.</p><p>From the root of the project, use the docker-compose command to run the container:</p><pre>$ docker-compose up</pre><p>By default, docker-compose looks for a file in the working directory called docker-compose.yaml. If there are no errors, you&#39;ll see a mess of log entries in your terminal. Once it&#39;s settled, check for these lines near the top:</p><pre>Creating network &quot;meanurls_default&quot; with the default driver<br>Creating volume &quot;meanurls_mean_urls_data&quot; with default driver<br>Creating mean_urls_db ... done</pre><p>This shows that the network and the volume were created correctly.</p><p>Scanning through the logs, check for this entry:</p><pre>mean_urls_db | Successfully added user: {<br>mean_urls_db |  &quot;user&quot; : &quot;app_user&quot;,<br>mean_urls_db |  &quot;roles&quot; : [<br>mean_urls_db |          {<br>mean_urls_db |                  &quot;role&quot; : &quot;dbOwner&quot;,<br>mean_urls_db |                  &quot;db&quot; : &quot;MeanUrls&quot;<br>mean_urls_db |          }<br>mean_urls_db |  ]<br>mean_urls_db | }</pre><p>This helps confirm that mongoInit.js was run and that a user was created for the application.</p><p>Using MongoDB Compass, the mongo shell, or your database browser of choice, connect to the database using this connection string:</p><pre>mongodb://app_user:app_user()@localhost:28017/MeanUrls</pre><p>You should see that the MeanUrls database and the Urls collection were created.</p><p>Run the application again as shown above and navigate to http://localhost:4200. The application should be running in the browser without receving any errors from the API. Lastly, enter a URL to shorten in the application. The object should be saved and everything working as expected:</p><figure><img alt="A browser view showing the application working as expected" src="https://cdn-images-1.medium.com/max/880/0*QVPjg0wLYK7dTFag.png" /></figure><h3>Seeding the database</h3><p>The next step is optional, but there are times when it’s helpful to start the database with some boilerplate data to test the components more authentically, or to see how the application handles a more realistic volume of data. The docker exec command lets us enter the Docker container from the terminal, navigate the file system on the container, and execute bash commands.</p><p>With the container running as in the previous step, execute the following command:</p><pre>$ docker exec -it mean_urls_db bash</pre><p>This will open a bash terminal running inside of the container.</p><p>If your container is configured as above, navigate to the directory where the seed scripts were mounted:</p><pre>$ cd /home/mongodb/seed</pre><p>Run the seed script:</p><pre>$ bash mongo_seed.sh</pre><p>If your output is similar to…</p><pre>2021-02-17T20:46:39.307+0000    connected to: mongodb://localhost/<br>2021-02-17T20:46:39.309+0000    50 document(s) imported successfully. 0 document(s) failed to import.</pre><p>… then you should be good to go.</p><p>Now, refresh the application in your web browser, or inspect the database with MongoDB Compass, and you should see that 50 fake documents have been added to the Urls collection.</p><p>To exit the container, type exit.</p><h3>Cleanup and some helpful scripts</h3><p>If I want to shut down the MongoDB server, I can run:</p><pre>$ docker-compose down</pre><p>This will stop and remove the Mongo container, but the volume where data is stored will persist when we start up the container again.</p><p>To remove the volume run:</p><pre>$ docker volume rm meanurls_mean_urls_data</pre><p>The next time I start the MongoDB container, the initialization scripts will run again.</p><p>If you’re living dangerously, you can also put the two together:</p><pre>$ docker-compose down -v</pre><p>Lastly, in projects, I like to include all of the container startup and teardown scripts in the package.json for convenience:</p><pre>{<br>  &quot;...&quot;: &quot;...&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;mongo&quot;: &quot;docker-compose up&quot;,<br>    &quot;mongo:up&quot;: &quot;docker-compose up&quot;,<br>    &quot;mongo:down&quot;: &quot;docker-compose down&quot;,<br>    &quot;mongo:clean&quot;: &quot;docker volume rm meanurls_mean_urls_data&quot;,<br>  }</pre><h3>Conclusion</h3><p>And with that, we’ve created a MongoDB server that communicates with a Node.js application from a container. This gives our application a dedicated MongoDB instance that’s easier to set up and tear down. We’ve also got a good foundation for getting configurations right in local development before replicating those consistently in higher environments. Lastly, we can re-configure and evolve the database server as the application changes without affecting other applications that would otherwise share the database server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac8f8219a019" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/dockerizing-a-mongo-database-ac8f8219a019">Dockerizing a Mongo Database</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Modern MEAN-stack with Angular and Typescript (Part 1)]]></title>
            <link>https://medium.com/swlh/a-modern-mean-stack-with-angular-and-typescript-part-1-2aba0eadcebe?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aba0eadcebe</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[mongo]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 23:07:11 GMT</pubDate>
            <atom:updated>2021-01-21T23:07:11.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*snxOE0fF1Faivb_cBDyB4w.jpeg" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@toluobde?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Tolu Olubode</strong></a><strong> on </strong><a href="https://unsplash.com/s/photos/construction?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><h3>Introduction</h3><p>One of the advantages I love about using <a href="https://angular.io/">Angular</a> is that the framework is truly <a href="https://chariotsolutions.com/presentation/single-page-application-day-angular-the-batteries-included-enterprise-spa-framework-rich-freedman/">“batteries included”</a>. From the application architecture, to configuration, to third-party libraries, to testing setup, to extra compilation tools, it’s a set of really smart decisions that help get a fully featured browser application running quickly. For tasks like setting up scripts, compiling Typescript, CSS preprocessing, Webpack, and testing, the Angular CLI can save lots of tedious configuration.</p><p>Likewise, for independent projects, <a href="https://nodejs.org/en/">Node.js</a> and <a href="https://expressjs.com/">Express</a> can be great choices as they tend to be easy to deploy to a variety of platforms.</p><p>Combined with <a href="https://www.mongodb.com/1">MongoDb</a> for data persistence, these tools have long been known as the <a href="https://en.wikipedia.org/wiki/MEAN_(solution_stack)">MEAN Stack</a> (with <a href="https://angularjs.org/">AngularJS</a> being the original <em>A</em> in MEAN), with “Javascript everywhere” being the unifying idea.</p><p>Over a few months of trying out different Angular-Express-With-Typescript setups, I’ve come up with a way to set up these kinds of projects using the <a href="https://cli.angular.io/">Angular CLI</a> as the starting point. After creating an Angular-based workspace, I can add an Express.js application written in Typescript, and configure the two to transpile Typescript files to a single deployable Node.js web app. With this set up, we can also use <a href="https://nodemon.io/">Nodemon</a> and <a href="https://www.npmjs.com/package/concurrently">Concurrently</a> to create a convenient dev workflow similar to what the Angular CLI provides with the ng serve --open command.</p><p>This article will be the first in a two-part series. In part one, we’ll go through setting up and configuring Angular and Express. Then we’ll use Nodemon, Concurrently, and <a href="https://www.npmjs.com/package/live-server">live-server</a> to handle compiling and refreshing the application when changes are made to the code base.</p><p>In the next tutorial, I’ll show how we can use Docker to serve the development database, a setup that’s a little more flexible and convenient than running MongoDb locally (although that’s perfectly fine too).</p><h3>Prerequisites</h3><p>This tutorial will assume at least some familiarity with Angular and the Angular CLI, Typescript and its CLI, and Express.</p><p>The following tools should be installed before starting (the links are to their respective “Getting Started” pages).</p><ul><li><a href="https://nodejs.org/en/download/">Node.js</a> — I’m using version 14.15.1 as I write this.</li><li><a href="https://angular.io/cli">Angular CLI</a> — I’m using version 11. If you’re a few version behind, these steps should still work.</li><li><a href="https://www.npmjs.com/package/typescript">Typescript</a> — I’m using version 4.</li></ul><p>We’ll also install a couple of NPM tools globally, but I’ll explain those as we come to them.</p><h3>Set up an empty Angular project</h3><p>The first step will be to use the Angular CLI to set up an Angular workspace so that we can take advantage of all of the framework’s smart default configurations from the start.</p><p>Normally, we would use the ng new command to create the project which would scaffold a few application components and tests to get us going. However, in our first step, we&#39;re going to set up the workspace and the application separately.</p><p>Start with this command:</p><pre>$ ng new NameApp --create-application=false --new-project-root=. --skip-install=true</pre><p>Notice some new flags:</p><ul><li>--create-application=false just sets up the workspace.</li><li>--new-project-root=. will help any configuration files (tsconfig.json, angular.json) find all of the locations in our project with minimal headaches.</li><li>--skip-install=true skips installing the node_modules packages. Since Angular comes with a ton of dependencies, we&#39;ll do our npm install all at once later on. This makes it easier to delete the entire project and start over if something doesn&#39;t turn out right.</li></ul><p>Now we’ll cd into the project directory and create the client application:</p><pre>$ cd NameApp<br>$ ng generate application client --skip-install=true</pre><p>You’ll be prompted to select if you want to add routing to the project, and your preferred CSS library.</p><p>We just created the usual, scaffolded Angular directories in a client directory. Now we can keep separate directories for our client-side and server-side code.</p><p>Note that if you add --dry-run or -d to the end of both of these command, this runs the command without actually adding new files, allowing you to see how the project will be layed out first, which is very convenient for experimenting with unconventional setups.</p><p>If all the directories look correct, run npm install to install all of the Node.js packages.</p><p>With everything installed, run ng serve --open and test that the default application is working in a browser as expected.</p><h3>Install some packages to support Express</h3><p>Now that a basic browser application is working, we’ll create an Express.js application that we’ll write in Typescript. Everything will live in a directory called server and we&#39;ll structure it in a similar setup to a typical Javascript Express application.</p><p>In the project’s root folder, we’ll install the main dependencies we’ll need:</p><pre>$ npm install express<br>$ npm install --save-dev @types/express</pre><p>We’ve added Express as our API server, and we’ve added the Typescript type definitions for Express.</p><p>Next, we’ll set up some files and directories for the server-side code:</p><pre>$ mkdir -p server/bin<br>$ touch server/app.ts<br>$ touch server/bin/www</pre><p>All of the server-side code will live in server. The bin/www file is a typical entry point file for an Express app, and app.ts will be the root application file that will assemble all of the middleware for the API.</p><p>In an editor, open bin/www and paste the following:</p><pre>#!/usr/bin/env node</pre><pre>/**<br> * Module dependencies.<br> */</pre><pre>const app = require(&#39;../app&#39;).default();<br>const debug = require(&#39;debug&#39;)(&#39;NameApp:server&#39;);<br>const http = require(&#39;http&#39;);<br>/**<br> * Get port from environment and store in Express.<br> */</pre><pre>const port = normalizePort(process.env.PORT || &#39;3000&#39;);<br>app.set(&#39;port&#39;, port);</pre><pre>/**<br> * Create HTTP server.<br> */</pre><pre>const server = http.createServer(app);</pre><pre>/**<br> * Listen on provided port, on all network interfaces.<br> */</pre><pre>server.listen(port, () =&gt; console.log(`Application is listening on port ${ port }`));<br>server.on(&#39;error&#39;, onError);<br>server.on(&#39;listening&#39;, onListening);</pre><pre>/**<br> * Normalize a port into a number, string, or false.<br> */</pre><pre>function normalizePort(val) {<br>  const port = parseInt(val, 10);</pre><pre>  if (isNaN(port)) {<br>    // named pipe<br>    return val;<br>  }</pre><pre>  if (port &gt;= 0) {<br>    // port number<br>    return port;<br>  }</pre><pre>  return false;<br>}</pre><pre>/**<br> * Event listener for HTTP server &quot;error&quot; event.<br> */</pre><pre>function onError(error) {<br>  if (error.syscall !== &#39;listen&#39;) {<br>    throw error;<br>  }</pre><pre>  const bind = typeof port === &#39;string&#39;<br>    ? &#39;Pipe &#39; + port<br>    : &#39;Port &#39; + port;</pre><pre>  // handle specific listen errors with friendly messages<br>  switch (error.code) {<br>    case &#39;EACCES&#39;:<br>      console.error(bind + &#39; requires elevated privileges&#39;);<br>      process.exit(1);<br>      break;<br>    case &#39;EADDRINUSE&#39;:<br>      console.error(bind + &#39; is already in use&#39;);<br>      process.exit(1);<br>      break;<br>    default:<br>      throw error;<br>  }<br>}</pre><pre>/**<br> * Event listener for HTTP server &quot;listening&quot; event.<br> */</pre><pre>function onListening() {<br>  const addr = server.address();<br>  const bind = typeof addr === &#39;string&#39;<br>    ? &#39;pipe &#39; + addr<br>    : &#39;port &#39; + addr.port;<br>  debug(&#39;Listening on &#39; + bind);<br>}</pre><p>This is almost exactly what gets generated when scaffolding a typical Express application with javascript and it basically pulls in our application code to create an HTTP server in the Node.js runtime. This file will most likely stay unchanged throughout any project.</p><p>Next, open app.ts and we&#39;ll paste in a very minimal Express setup:</p><pre>import * as express from &#39;express&#39;;<br>import { Express, Request, Response } from &#39;express&#39;;</pre><pre>export default function createApp(): Express {<br>    const app = express();<br>    app.get(&#39;/api/:name&#39;, async (req: Request, res: Response) =&gt; {<br>        const name = req.params.name;<br>        const greeting = { greeting: `Hello, ${ name }` };<br>        res.send(greeting);<br>    });<br>    return app;<br>}</pre><p>Not much going on here. So far, what we can expect is that when we run the server, a GET request to /api/Artie will return Hello, Artie.</p><p>Now we need to process the Typescript file and output them as Javascript that the Node.js runtime can read.</p><h3>Setting up a build artifacts directory</h3><p>Our intention is to output all of the Javascript code to a ./dist directory in the root of the project. This is the directory that Angular normally compiles all of its browser code to, and it&#39;s already in the .gitignore that Angular created. We&#39;ll modify ./dist to instead end up with a unified deployment package once the Angular and Express code is all processed. At the end, all of our Typescript scripts will be output to the ./dist directory as follows:</p><pre>/dist<br> - /api<br>    - /bin/www<br>    - app.js<br>    # (... everything we made with Express ...)<br> - /public<br>    # (... everything we made with Angular)</pre><p>With the Angular code, we only need to make a small change to the angular.json file.</p><pre>{<br>  // ...<br>  &quot;projects&quot;: {<br>    &quot;client&quot;: {<br>      &quot;architect&quot;: {<br>        &quot;build&quot;: {<br>          &quot;options&quot;: {<br>            &quot;outputPath&quot;: &quot;dist/public&quot;,  // &lt;--- CHANGE THIS PATH</pre><p>The rest of the Angular configurations should be okay as they are.</p><p>For our server-side code, we’ll add a separate tsconfig file in the ./server directory:</p><pre>$ touch ./server/tsconfig.api.json</pre><p>Add these values:</p><pre>{<br>    &quot;compilerOptions&quot;: {<br>      &quot;baseUrl&quot;: &quot;../&quot;,<br>      &quot;module&quot;: &quot;CommonJS&quot;,<br>      &quot;resolveJsonModule&quot;: false,<br>      &quot;esModuleInterop&quot;: false,<br>      &quot;target&quot;: &quot;ESNext&quot;,<br>      &quot;outDir&quot;: &quot;../dist/api&quot;,<br>      &quot;sourceMap&quot;: true,<br>      &quot;types&quot;: [<br>        &quot;node&quot;<br>      ],<br>      &quot;experimentalDecorators&quot;: true,<br>      &quot;emitDecoratorMetadata&quot;: true<br>    }<br>  }</pre><p>The important settings to note is that the baseUrl value is still the root of the project so that it draws from the same node_modules library. Then outDir is set to the same ./dist directory where all of the compiled output goes.</p><p>With our first app.ts iteration written, and our configurations updated, we now need to transpile the file to Javascript and make sure that the bin/www file can load it. We&#39;ll do the following test:</p><p>Create a ./dist directory with an api/bin directory at the root of the project if there isn&#39;t one there already. Then copy the www file:</p><pre>$ mkdir -p ./dist/api/bin<br>$ cp ./server/bin/www ./dist/api/bin</pre><p>Now, with the Typescript compiler, we’ll turn app.ts into Javascript output:</p><pre>$ tsc -p ./server/tsconfig.api.json</pre><p>Double check that it has been created ./dist/api/app.js.</p><p>Run the www with Node to see if the Express.js server runs and accepts a test GET request as expected:</p><pre>$ node ./dist/api/bin/www</pre><p>In another terminal:</p><pre>$ curl <a href="http://localhost:3000/api/Artie">http://localhost:3000/api/Artie</a></pre><p>And we should see {&quot;greeting&quot; : &quot;Hello, Artie&quot;} returned to the terminal.</p><h3>Setting up scripts for unified client and server-side development</h3><p>At this point you should have gotten signs of life from both the Angular and the Express apps. Now we need to combine the two so that we can serve the entire application on a single port. To do this, we’ll set up Angular to build to the ./dist/public, then set the Express server to serve the static files from that directory.</p><p>First, we’ll set Express to serve static files from ./dist/public. Here is app.ts with those lines added:</p><pre>import * as express from &#39;express&#39;;<br>import * as path from &#39;path&#39;;  // &lt; -- add this<br>import { Express, Request, Response } from &#39;express&#39;;</pre><pre>export default function createApp(): Express {<br>    const app = express();<br>    const clientDir = path.join(__dirname, &#39;../public&#39;);  // &lt;-- add this <br>    app.use(express.static(clientDir));                   // &lt;-- and add this<br>    app.get(&#39;/api/:name&#39;, async (req: Request, res: Response) =&gt; {<br>        const name = req.params.name;<br>        const greeting = { greeting: `Hello, ${ name }` };<br>        res.send(greeting);<br>    });<br>    return app;<br>}</pre><p>Note that the location of public is relative to the compiled app.js when it&#39;s in the ./dist/api directory.</p><p>Now, the following commands will 1) Build the static assets from Angular, 2) transpile the changes added to app.ts, and 3) serve the entire application from Express as before:</p><pre>$ ng build<br>$ tsc -p ./server/tsconfig.api.json<br>$ node ./dist/api/bin/www</pre><p>Navigate to http://localhost:3000 and you should see the default Angular page again. Make a GET request to http://localhost:3000/api/Oliver and you should get {&quot;greeting&quot; : &quot;Hello, Oliver&quot;} as the response.</p><p>Shut the server down and proceed.</p><p>With Express serving both the API and the static browser files, we’ll add some scripts to the package.json file to make all of these steps more seamless and so the server can listen to file changes.</p><p>First, we’ll need to install the following npm tools globally:</p><ul><li>npm install --global nodemon - Nodemon is a development utility that will restart our API server whenever changes to the code are detected.</li><li>npm install --global concurrently - Concurrently is a tool that can run multiple npm processes in the same terminal, and it provides several options to deal with any of the processes failing. We&#39;ll use concurrently to watch and rebuild the client and server side code at the same time.</li></ul><p>Now add the following scripts to package.json:</p><pre>{<br>    // ...<br>    &quot;scripts&quot;: {<br>        //...<br>        &quot;clean&quot;: &quot;rm -rf ./dist/api &amp;&amp; rm -rf ./dist/public/&quot;,<br>        &quot;cp:www&quot;: &quot;mkdir -p ./dist/api/bin &amp;&amp; cp ./server/bin/www ./dist/api/bin/&quot;,<br>        &quot;dev&quot;: &quot;concurrently -k \&quot;tsc -p ./server/tsconfig.api.json -w\&quot; \&quot;cd ./dist/api &amp;&amp; nodemon -r ./bin/www --watch\&quot; \&quot;ng build --watch\&quot;&quot;<br>    }<br>}</pre><p>Here’s what they do:</p><ul><li>$ npm run clean - will clean out the directories where the compiled output goes in case we need to make a fresh start.</li><li>$ npm run cp:www - This copies ./server/bin/www to its proper location.</li><li>$ npm run dev - Using Concurrently, we compile Typescript files every time there are changes, run the files in Node and watch for changes with Nodemon, then watch for changes to the Angular files and build those accordingly.</li></ul><p>Run each of those scripts in order and you should get the same results as above when making requests to <a href="http://localhost:3000.">http://localhost:3000.</a></p><h3>Bonus: Refresh the browser when client-side code changes</h3><p>Unfortunately, one of the tradeoffs to using the above scripts instead of Angular’s ng serve is that we&#39;d have to manually refresh the browser each time we make changes. Configuring Express with a couple of npm packages - livereload and connect-livereload - can accomplish this in our current setup.</p><p>Install the packages as development dependencies:</p><pre>$ npm install --save-dev livereload connect-livereload</pre><p>In app.ts, import the libraries:</p><pre>import * as livereload from &#39;livereload&#39;;<br>import * as connectLivereload from &#39;connect-livereload&#39;;</pre><p>And underneath the line where the client directory is declared, paste the following:</p><pre>const app = express();<br>  const clientDir = path.join(__dirname, &#39;../public&#39;);</pre><pre>  // In development, refresh Angular on save just like ng serve does<br>  let livereloadServer: any;<br>  if (process.env.NODE_ENV !== &#39;production&#39;) {<br>      livereloadServer = livereload.createServer();<br>      livereloadServer.watch(clientDir);<br>      app.use(connectLivereload());<br>      livereloadServer.once(&#39;connection&#39;, () =&gt; {<br>        setTimeout(() =&gt; livereloadServer.refresh(&#39;/&#39;), 100);<br>      });<br>  }</pre><p>In the code, we’re creating a livereload server and setting it to listen to changes to the client directory. Then, connect-livereload provides middleware to the Express app that injects a bit of temporary code in our static files that makes the browser aware of any changes and refreshes accordingly.</p><p>Lastly, if your linter is giving you grief about not having type declarations for livereload and connect-livereload, you can add a type declarations file in the server directory:</p><pre>$ touch ./server/decs.d.ts</pre><p>And paste the following:</p><pre>declare module &#39;livereload&#39;;<br>declare module &#39;connect-livereload&#39;;</pre><p>I got this configuration mainly from <a href="https://bytearcher.com/articles/refresh-changes-browser-express-livereload-nodemon/">this article</a> which goes into much more detail about what is actually happening.</p><h3>Putting it all together</h3><p>As one final proof-of-life, let’s get our Angular application to talk to the Express back end.</p><p>In the Angular app, open app.module.ts and paste the all of the following:</p><pre>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { HttpClientModule } from &#39;@angular/common/http&#39;;</pre><pre>import { AppComponent } from &#39;./app.component&#39;;</pre><pre>@NgModule({<br>  declarations: [<br>    AppComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    FormsModule,<br>    HttpClientModule<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>The only difference is that we’ve added the FormsModule and the HttpClientModule.</p><p>Next open app.component.ts and replace the entire file with:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;div class=&quot;app-container&quot; style=&quot;width:20rem; margin: 2rem auto;&quot;&gt;<br>      &lt;div class=&quot;form-group&quot; &gt;<br>        &lt;label for=&quot;name-input&quot;&gt;Enter a name:&lt;/label&gt;<br>        &lt;input class=&quot;form-control&quot; id=&quot;name-input&quot; required [(ngModel)]=&quot;nameInput&quot;&gt;<br>        &lt;button class=&quot;btn btn-primary&quot;(click)=&quot;greetMe()&quot;&gt;Greet Me&lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;name-display&quot;&gt;<br>        &lt;p *ngIf=&quot;responseDisplay &amp;&amp; responseDisplay.length &gt; 0&quot;&gt;<br>          {{ responseDisplay }}<br>        &lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class AppComponent {</pre><pre>  constructor(private http: HttpClient) {  }</pre><pre>  nameInput: string = &#39;&#39;;<br>  responseDisplay: string = &#39;&#39;;</pre><pre>  greetMe(): void {<br>    this.http.get(`/api/${ this.nameInput }`)<br>      .subscribe((response: any) =&gt; this.responseDisplay = response.greeting);<br>  }<br>}</pre><p>Optionally, you can add some basic Bootstrap so the result isn’t hideous. In styles.css, add:</p><pre>/* You can add global styles to this file, and also import other style files */<br>@import url(https://medium.com/&#39;https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css&#39;);</pre><p>Run the entire application again with $ npm run dev, and you should see a tiny form where you can send a name to the server, then get a greeting back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*b4ejcgZihwoAcgdr6mzysw.jpeg" /></figure><h3>Conclusion</h3><p>The above steps should provide a good start to building out a fullstack application entirely in Typescript. By starting with Angular, we’re bringing in a rich set of tools and configurations, then adding Express.js and some scripts for a convenient and automated development workflow.</p><p>In part 2 of this tutorial, I’ll show how to add in MongoDb (the <strong>M</strong> in <strong>MEAN</strong>) and how to use Docker to reduce some of the overhead in setting up a local database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aba0eadcebe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-modern-mean-stack-with-angular-and-typescript-part-1-2aba0eadcebe">A Modern MEAN-stack with Angular and Typescript (Part 1)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Quickly Mock an API Server in a Client-Side Project]]></title>
            <link>https://medium.com/swlh/how-to-quickly-mock-an-api-server-in-a-client-side-project-aa503ecfa9cf?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa503ecfa9cf</guid>
            <category><![CDATA[client-side-web]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Fri, 15 Jan 2021 22:01:07 GMT</pubDate>
            <atom:updated>2021-01-17T15:26:16.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*UY9iFyuv6-xvu8ctWPDNRQ.jpeg" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@larskienle?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Lars Kienle</strong></a><strong> on </strong><a href="https://unsplash.com/s/photos/mock-data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><h3>Introduction</h3><p>In this post I’d like to demonstrate two simple tools that you can use to simulate fetching data from an API that can greatly facilitate frontend web development. This can be helpful for focusing on UI development without worrying about the server-side implementation of the project. It can also be helpful for setting up a proof-of-concept projects without having to worrying about protecting real data, or for setting up consistent fake data for end-to-end testing. The two tools I’ll demonstrate are <a href="https://www.mockaroo.com/">Mockaroo</a> for generating sets of dummy data, and <a href="https://github.com/typicode/json-server">json-server</a> for creating a fake API that a front-end application can make requests to.</p><h3>Prerequisites</h3><p>This tutorial is aimed squarely at folks getting familiar writing browser-side code with HTML, CSS, and Javascript. That said, these tools can help support more robust front-end projects as well. If you’ve got a bit of knowledge of HTML and Javascript and some familiarity with the command line, then you’ll be able to get the tools in this article to work for you.</p><p>Before we start, you’ll need the following installed:</p><ul><li><a href="https://nodejs.org/">Node.js</a>. I’m using version 14 as I write this, but any LTS version should do.</li><li>Some way of serving static HTML and Javascript files locally. I use <a href="https://github.com/http-party/http-server#readme">http-server</a> and it’s fast and really simple, but there are several other options.</li></ul><p>To get started, create a tiny web project that’ll consist of just an HTML page and a JSON file to will hold our fake data:</p><pre>$ mkdir file_viewer<br>$ cd field_viewer<br>$ touch index.html db.json</pre><p>These files can stay empty for now; We’ll paste in a little bit of code at the end of this tutorial to get it all working.</p><h3>Step one: Data modeling</h3><p>I’m imagining a web application that allows users to upload files, then it shows a list of all the files that have been saved.<br>For this very simple example, we’ll create a mock backend for an API that lists all of the file metadata (e.g., file name, file type, date created) after uploading.</p><p>Before generating mock data, we need to get some idea of what our data will look like, what properties each object will have when it’s returned from the API. We’ll need to know the properties we want and what primitive Javascript type they’ll be. Our file metadata can look something like this:</p><pre>id: number<br>fileName: string<br>fileType: string<br>createdDate: Date<br>email: string<br>active: boolean</pre><p>An example json object with those properties might look like:</p><pre>{<br>    &quot;id&quot;: 30,<br>    &quot;fileName&quot;: &quot;The Chrysanthemum and the Dandelion&quot;,<br>    &quot;fileType&quot;: &quot;.pdf&quot;,<br>    &quot;createdDate&quot;: &quot;2020-11-18T01:36:46Z&quot;,<br>    &quot;email&quot;: &quot;kuni@garu.com&quot;,<br>    &quot;active&quot;: true<br>}</pre><h3>Step two: Generate mock data with Mockaroo</h3><p>Now that we have an idea of what our data looks like, we can use <a href="https://www.mockaroo.com/">Mockaroo</a>, a browser-based tool that can generate thousands of realistic looking records for us. Mockaroo has a variety of subscription-based utilities for creating mock APIs, but for this demonstration we’ll use it for basic mock data generation which we can do for free.</p><p>The first part of Mockaroo is a form for adding properties to our mock data objects. Play around with the different data types that they offer and you’ll see it can generate random data for a wide range of situations. Many of the data types have settings to further customize what gets generated. You can customize the behavior further by passing values through your own functions. Below, I’ll create settings for each of the properties in our file metadata object, but feel free to add and change anything you find that’s interesting. The rest of this tutorial will still work.</p><p>Below you can see the settings that I selected for the mock data object above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*8db5ZHso8sxtZoiasrn_Ug.jpeg" /></figure><p><strong>id:</strong> For this field, I selected the <strong>Row Number</strong> data type which will number all of the records in order. This will help with fetching individual records from our fake API further on in this article.</p><p><strong>fileName</strong> and <strong>email:</strong> For these two properties, Mockaroo can generate realistic random values by searching for and selecting the <strong>File Name</strong> and <strong>Email</strong> types respectively.</p><p><strong>createdDate and active:</strong> For the createdDate, I can use Mockaroo&#39;s <strong>Datetime</strong> type and set it to return an ISO date which Javascript can parse, and I&#39;ve set it to return dates from the past year. For the active property (which indicates if our file has been deleted or not), I can return a boolean.</p><p><strong>fileType:</strong> For file types, I’d like my application to only allow Microsoft Word, Excel, and PDF files to be used, so in Mockaroo, I’ll use a custom function to populate those values. Mockaroo allows us to write functions in Ruby to allow values to be transformed before returning. I’m going to click the <strong>fx</strong> button for the fileType row and add the following:</p><pre>[&#39;.docx&#39;, &#39;.xlsx&#39;, &#39;.pdf&#39;].sample</pre><p>This will randomly select one item from that array and return it.</p><p>Now that my data objects are defined, I’ll select <strong># Rows: 100</strong> and <strong>Format: JSON</strong> from the bottom of the form. I’ll also select <strong>array</strong> and deselect <strong>include null values</strong>. Again, this is what my Mockaroo form looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*8db5ZHso8sxtZoiasrn_Ug.jpeg" /></figure><p>I’ll click the <strong>Preview</strong> button to make sure my objects look like what I expect, then click <strong>Download Data</strong> to save it as a JSON file.</p><h3>Serving the mock data with json-server</h3><p>Now that we have some data, let’s create a fake server that we can fetch it from.</p><p><a href="https://github.com/typicode/json-server">json-server</a> is a very light Node.js tool that can allow a frontend developer to define some API endpoints and sets of data that can be returned to a client application. This way, the mock data is completely separate from the client-side code and it can be switched out once the project is ready for a real API. In this article, we’ll just set up the server and make a GET request to it, but json-server can also POST and save objects as well as more advanced uses.</p><p>First, install the json-server npm package globally:</p><pre>$ npm install -g json-server</pre><p>Open the file at the root of the FileViewer directory - ./db.json - that you created above. This will hold all of the json data:</p><p>As a quick test just to make sure it works, paste the following into db.json:</p><pre>{<br>  &quot;posts&quot;: [<br>    { &quot;id&quot;: 1, &quot;title&quot;: &quot;json-server&quot;, &quot;author&quot;: &quot;typicode&quot; }<br>  ],<br>  &quot;comments&quot;: [<br>    { &quot;id&quot;: 1, &quot;body&quot;: &quot;some comment&quot;, &quot;postId&quot;: 1 }<br>  ],<br>  &quot;profile&quot;: { &quot;name&quot;: &quot;typicode&quot; }<br>}</pre><p>This comes directly from the <a href="https://github.com/typicode/json-server#readme">json-server documentation</a>.</p><p>Run the json server with this command:</p><pre>$ json-server --watch db.json</pre><p>In a browser, paste in http://localhost:3000/posts/1 and it should return the first object in the posts array in our json file:</p><pre>{ &quot;id&quot;: 1, &quot;title&quot;: &quot;json-server&quot;, &quot;author&quot;: &quot;typicode&quot; }</pre><p>Now that we know the server is working, stop the server (CTRL+C).</p><p>Open db.json again and clear the contents. We&#39;ll define an endpoint for our mock data called files:</p><pre>{<br>    &quot;files&quot;: []<br>}</pre><p>Open the JSON file that was downloaded from Mockaroo (it should be called MOCK_DATA.json). Copy all of the contents. Replace the empty &quot;files&quot; array with these contents so it looks something like this:</p><pre>{<br>    &quot;files&quot;: [<br>        {&quot;id&quot;:1,&quot;fileName&quot;:&quot;nulla.xls&quot;,&quot;fileType&quot;:&quot;.xlsx&quot;,&quot;createdDate&quot;:&quot;2020-02-27T05:10:27Z&quot;,&quot;email&quot;:&quot;hweiner0@wikimedia.org&quot;,&quot;active&quot;:true},<br>        {&quot;id&quot;:2,&quot;fileName&quot;:&quot;sapien urna.png&quot;,&quot;fileType&quot;:&quot;.xlsx&quot;,&quot;createdDate&quot;:&quot;2020-12-20T05:12:00Z&quot;,&quot;email&quot;:&quot;creding1@google.com.br&quot;,&quot;active&quot;:false},<br>        {&quot;id&quot;:3,&quot;fileName&quot;:&quot;vel augue.ppt&quot;,&quot;fileType&quot;:&quot;.docx&quot;,&quot;createdDate&quot;:&quot;2020-10-03T05:06:18Z&quot;,&quot;email&quot;:&quot;ccrust2@theguardian.com&quot;,&quot;active&quot;:true},<br>        {&quot;id&quot;:4,&quot;fileName&quot;:&quot;mauris morbi non.txt&quot;,&quot;fileType&quot;:&quot;.docx&quot;,&quot;createdDate&quot;:&quot;2020-04-26T13:44:41Z&quot;,&quot;email&quot;:&quot;nfolbig3@livejournal.com&quot;,&quot;active&quot;:true},<br>        {&quot;id&quot;:5,&quot;fileName&quot;:&quot;sapien sapien non.ppt&quot;,&quot;fileType&quot;:&quot;.pdf&quot;,&quot;createdDate&quot;:&quot;2020-04-16T17:56:06Z&quot;,&quot;email&quot;:&quot;cdesimoni4@uol.com.br&quot;,&quot;active&quot;:true},</pre><pre>        // ...</pre><pre>    ]<br>}</pre><p>Run json-server again and request the /files endpoint: <a href="http://localhost:3000/files.">http://localhost:3000/files.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*JCZ84BYRHkq2AXJHZ67_nQ.jpeg" /></figure><p>It should load all 100 of the fake records that Mockaroo generated. Add an id number at the end of the url (http://localhost:3000/files/42) and it should return the one record with that id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*89TiQfR97_55CJ04SXWAFg.jpeg" /></figure><p>Finally, we can make an AJAX request from inside of our (tiny) web application to make sure it can connect with our front end code.</p><p>Open the index.html file that was created earlier and paste the following:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;File Viewer&lt;/title&gt;<br>    &lt;link href=&quot;css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;File Viewer&lt;/h1&gt;</pre><pre>    &lt;script&gt;<br>        fetch(&#39;http://localhost:3000/files&#39;)<br>          .then(response =&gt; response.json())<br>          .then(data =&gt; console.log(&#39;Data from our mock backend: &#39;, data));<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Open a separate terminal window and cd into the FileViewer project created above. Start an HTTP server from this location (if you installed <a href="https://github.com/http-party/http-server#readme">http-server</a>, the command is just $ http-server --open).</p><p>In a browser, navigate to the http-server url (it would be http://localhost:8080 by default) and open a dev tools console. The page should have printed the mock data to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*EXhKyaWKkRMQyifpBSz0YA.jpeg" /></figure><h3>Conclusion</h3><p>In this tutorial, we walked through a very basic way to define data for a web application, generate hundreds of realistic records, then serve them from a mock API that can be consumed by the application. This is only a very bare minimum implementation of these steps. I highly advise going through the <a href="https://www.mockaroo.com/">Mockaroo</a> and <a href="https://github.com/http-party/http-server#readme">json-server</a> documentation for a wide variety of other uses and configurations that can suit your frontend development needs even more closely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa503ecfa9cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-quickly-mock-an-api-server-in-a-client-side-project-aa503ecfa9cf">How to Quickly Mock an API Server in a Client-Side Project</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuration in ASP.NET Core Explained]]></title>
            <link>https://medium.com/swlh/configuration-in-asp-net-core-explained-e98e83963283?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/e98e83963283</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[webapi]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 13:52:48 GMT</pubDate>
            <atom:updated>2020-12-12T21:52:35.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*2SKAeVgSKIo4DYgdwz9_4A.jpeg" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@intelligenciya?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Alexey Ruban</strong></a><strong> on </strong><a href="https://unsplash.com/s/photos/recording-console?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><p>A common consideration for working with an ASP.NET Core application is how to store and retrieve values in configuration settings, as well as how to change and update them as the application moves to higher environments. It’s common to need sensitive values like passwords, API keys, and database connection strings in order to call out to other services, and these settings must be stored separately from the application’s source code. To help manage this process, ASP.NET Core contains a set of configuration providers for retrieving and storing values, as well as a class to make complex settings available in the application as strongly-typed objects.</p><p>In this tutorial, I’ll use an extremely simple web API to illustrate the different configuration providers and how one overrides the next as the application moves to different environments. We’ll start with some boilerplate code, create a class to hold configuration settings, then load those settings from different locations in the file system. Finally, we’ll move the application to a Docker container to show how settings can be updated in different environments.</p><h3>Prerequisites</h3><p>I’ll assume you have some familiarity with ASP.NET Core applications, but this article will still stay at a beginner level. To build a copy of the example application and follow along, you will need:</p><ol><li><a href="https://dotnet.microsoft.com/download">Version 3.1 of the .NET Core SDK</a> running on your development machine.</li><li><a href="https://www.docker.com/products/docker-desktop">Docker Desktop</a> running on your local machine. The version I’m using as of this writing is 19.03.12.</li><li><a href="https://www.postman.com/">Postman</a>, or an API tool of your choice, is recommended for making calls to the API and inspecting the results.</li><li>Lastly, to follow along with the examples, I’ve created a Github repo with a <strong>before</strong> and <strong>after</strong> branch. The following command will clone the repo:</li></ol><pre>$ git clone <a href="https://github.com/jsheridanwells/aspnetcore-config-example.git">https://github.com/jsheridanwells/aspnetcore-config-example.git</a></pre><p>To fetch the <strong>before</strong> and <strong>after</strong> branches, run:</p><pre>$ git fetch origin before:before <br>$ git fetch origin after:after</pre><p>Then, $ git checkout &lt;branch name&gt; will take you to before or after.</p><p>Lastly, I tend to prefer writing .NET Core tutorials as OS-agnostically as possible, so I’ll be using the command line with <strong>Bash</strong> for most of the steps, rather than Visual Studio. If you are using an IDE like Visual Studio or the Windows command line, there may be some differences from what you’ll see here.</p><h3>The boilerplate</h3><p>Here are the important files we’ll be working with in this project:</p><ul><li>appsettings.json and appsettings.Development.json are two configuration files provided by ASP.NET core for configuration settings in different environments. The first file, appsettings.json contains any default settings, then any appsettings.{Environment Name}.json files override those settings. Since these files are stored at the root of the project directory, they should not contain any sensitive keys as these settings will usually checked into the project&#39;s version control system.</li><li>Program.cs is the main file that scaffolds an ASP.NET Core application and creates both the application and the host environment for the application. In this project, you&#39;ll notice a method called .ConfigureAppConfiguration that is commented out. Later in this tutorial, we&#39;ll uncomment the method and play around with the directives in there.</li><li>Startup.cs defines all the top-level settings for the application including configuration, dependency in injection, and the middlewares used by the application. In this class, we&#39;ll define the entry point for the app&#39;s configuration.</li><li>Controllers/ConfigController.cs is the single controller in the project with a single method called GetConfig that will be modified to return the values in our settings so that we can inspect the configuration values that are available in the application.</li><li>Lastly, Dockerfile will be used to build the application in a container and experiment with passing in configuration values that way. Note that we won&#39;t discuss containerizing applications in this tutorial, but you won&#39;t need to know much Docker for this demo.</li></ul><p>If you run the project using the CLI…</p><pre>$ dotnet run</pre><p>… and make a GET request to http://localhost:5000/config, you should get &quot;nothing implemented yet&quot; as your response.</p><h3>Loading configuration in Startup.cs</h3><p>Best practice for loading configuration settings is to create a simple class to map the configuration values, then adding them in the Startup class.</p><p>In this demo, our configuration will consist of two keys: Id will hold a Guid that we can pretend is a secret value like an API key, and Location where we&#39;ll write the location of the configuration object (e.g., appSettings, user secrets, environment variables etc.). At the root of the project, create a file called MyConfig.cs and add the following C# code:</p><pre>using System;</pre><pre>namespace AspNetCoreConfigExample<br>{<br>    public class MyConfig<br>    {<br>        public Guid Id { get; set; }<br>        public string Location { get; set; }<br>    }<br>}</pre><p>Now, whenever we need these values, we can reference the section as &quot;MyConfig&quot;. In appsettings.json, the MyConfig section is set as follows:</p><pre>&quot;MyConfig&quot;: {<br>    &quot;Id&quot;: &quot;4c3c066c-928f-4de4-86b8-09365aed6a7c&quot;,<br>    &quot;Location&quot;: &quot;from appSettings.json&quot;<br>}</pre><p>In the Startup class, in the ConfigureServices method, we&#39;ll update the method as follows:</p><pre>// Add configuration section here<br>var configs = Configuration.GetSection(&quot;MyConfig&quot;);<br>services.Configure&lt;MyConfig&gt;(configs);</pre><p>Configuration.GetSection checks the configuration providers for any key named &quot;MyConfig&quot;, then tries to map them to the MyConfig class.</p><p>You can check that the project compiles by running $ dotnet build.</p><p>Next, open ./Controllers/ConfigController.cs.</p><p>To make the configuration values available to the class, we’ll add an IOptions&lt;T&gt; argument to the class constructor, and make the value of IOptions a private key.</p><pre>private MyConfig _configs;<br>public ConfigController(IOptions&lt;MyConfig&gt; opts)<br>{<br>    _configs = opts.Value;<br>}</pre><p>Finally, we’ll update the GetConfig method to return whatever is in the _configs property:</p><pre>[HttpGet]<br>public IActionResult GetConfig()<br>{<br>    // 3. return the config to inspect it<br>    var configs = _configs;<br>    return Ok(new { Result = &quot;config values: &quot;, configs });<br>}</pre><p>Now, run the application using the .NET CLI:</p><pre>$ dotnet run</pre><p>Make a GET request to http://localhost:5000/config, and the response should come back as follows:</p><pre>{<br>    &quot;id&quot;: &quot;4c3c066c-928f-4de4-86b8-09365aed6a7c&quot;,<br>    &quot;location&quot;: &quot;from appSettings.json&quot;<br>}</pre><p>From the above steps, we see how configuration is loaded through the Startup class, then made available to the application through the IOptions&lt;T&gt; class.</p><p>In the next steps, we’ll add new configurations in different locations to demonstrate the hierarchy of providers in ASP.NET Core and how one provider can override the next.</p><h3>The provider hierarchy</h3><p>The default configuration setup for an ASP.NET Core app is hidden away in the Program class, in a method called .ConfigureWebHostDefaults. By default, the method checks for settings in a hierarchy of locations and if a matching configuration is found after a preceding one, settings from the latter are used.</p><p><a href="https://devblogs.microsoft.com/premier-developer/order-of-precedence-when-configuring-asp-net-core/">According to this Microsoft blog</a>, this is the order that providers are used:</p><ol><li>The appsettings.json file</li><li>Any appsettings.{ ENVIRONMENT_NAME }.json files</li><li>User secrets from the .NET User Secrets Manager</li><li>Environment variables</li><li>Command line arguments</li></ol><p>All of this happens under the hood, allowing us to write the configuration code once in Startup without having to add conditions for different environments. In the next few sections, we&#39;ll go through each of these providers, and at the end I&#39;ll show to override the default provider order for custom scenarios.</p><h3>appsettings.json</h3><p>When we ran the application in the last step, the configuration values that were returned came from the ./appsettings.json file. This can be overridden with an appsettings.{ ENVIRONMENT NAME }.json file. Add a file at the root of the project called appsettings.Development.json and paste in the following:</p><pre>{<br>  &quot;MyConfig&quot;: {<br>    &quot;Id&quot;: &quot;6e20863b-ae31-4e6c-8711-00177586bec0&quot;,<br>    &quot;Location&quot;: &quot;from appSettings.development.json&quot;<br>  }<br>}</pre><p>Run the server again and make another get request to http://localhost:5000/config and the response will now show the values from the Development settings, which is the default environment when running an ASP.NET Core app from a local host. This is useful for storing connection strings to local databases or any generic configuration values that can be safely stored in a source control repository.</p><p>To see how a different environment can override these settings, create another files called appsettings.Staging.json and paste the following:</p><pre>{<br>    &quot;MyConfig&quot;: {<br>        &quot;Id&quot;: &quot;bd304170-b899-42a9-9f9f-048e6e67a5dd&quot;,<br>        &quot;Location&quot;: &quot;from appSettings.Staging.json&quot;<br>    }<br>}</pre><p>We’ll change the hosting environment to “Staging”, then run set the application to run with that profile:</p><pre>$ export ASPNETCORE_ENVIRONMENT=&quot;Staging&quot;<br>$ dotnet run --launch-profile &quot;Staging&quot;</pre><p>If you are using Windows, the first command is:</p><pre>&gt; set ASPNETCORE_ENVIRONMENT=&quot;Staging&quot;</pre><p>Now the request returns the settings from the Staging configuration.</p><h3>User Secrets Manager</h3><p>appsettings.json is okay for generic settings, but some other settings for development need to be stored separately from the source code. These could be API keys, passwords, settings for cloud infrastructure, or connections strings for remote databases. The .NET CLI provides a utility called the User Secrets Manager that can store and load values from a local development filesystem.</p><p>If you are using Visual Studio, you can right-click the name of the project in the Solution Explorer to get a user secrets dialog that makes managing these values automatic.</p><p>Using the .NET CLI, there are a few steps:</p><ol><li>At the root of the project, initialize the User Secrets Manager: $ dotnet user-secrets init.</li><li>The project will need a user secrets ID which can be any string. This is added to the .csproj file. For this project, there is already a GUID added:</li></ol><pre>&lt;!--AspNetCoreConfigExample.csproj--&gt;<br> &lt;PropertyGroup&gt;<br>&lt;!--    ...--&gt;<br>    &lt;UserSecretsId&gt;fa9be5ec-53e4-4275-8941-99cf83d8c344&lt;/UserSecretsId&gt;<br>&lt;/PropertyGroup&gt;</pre><ol><li>Using the cli, you can add new values for the Id and Location settings for the project:</li></ol><pre>$ dotnet user-secrets set MyConfig:Id fa3e83d5-27e2-4a02-ae75-ad3763985290<br> $ dotnet user-secrets set MyConfig:Location &#39;User Secrets Store&#39;</pre><p>Now, if you navigate to ~/.microsoft/usersecrets/&lt;user_secrets_id&gt;/secrets.json on your file system, you&#39;ll see a json file added that will map to the configuration settings as before. (Note: if you&#39;re using Windows, the path to the user secrets file is %APPDATA%\Microsoft\UserSecrets\&lt;user_secrets_id&gt;\secrets.json).</p><p>Run the application, make a request to /config again, and the values added with the User Secrets Manager have overridden the values from appsettings.json without having to modify any of the code.</p><p>Note that the User Secrets Manager is only for development purposes and should not be used in a production scenario since those values are stored on the host in plain text.</p><h3>Environment variables, command line arguments, and container commands</h3><p>We can also set MyConfig:Id and MyConfig:Location as environment variables and they will take precedent over the user secrets settings.</p><p>If you are using Linux or OSX, you can add these as environment variables:</p><pre>$ export MyConfig__Id=52a8f62b-43fa-4da6-8a7e-7b788402aeed<br>$ export MyConfig__Location=&quot;Environment Variable&quot;</pre><p>In Windows, the equivalent is:</p><pre>&gt; set MyConfig:Id=52a8f62b-43fa-4da6-8a7e-7b788402aeed<br>&gt; set MyConfig:Location=&quot;Environment Variable&quot;</pre><p>Once again, /config returns the environment variable settings.</p><p>We can also run the application with command-line arguments…</p><pre>$ dotnet run MyConfig:Id=be4209bc-8162-4c77-9064-8dd912b2a413 MyConfig:Location=&#39;command line&#39;</pre><p>… and get the same result. These could be very useful when scripting the program in different environments like a CI/CD pipeline.</p><p>Where this really comes in handy is when building the application as a container image. In the next few steps, we’ll Docker-ize the application three different ways. You won’t need any deep Docker knowledge to do this as long as you have Docker Desktop installed and running on your development machine (check $ docker --version to be sure).</p><p>The AspNetCoreConfigExample project contains a simple Dockerfile that is basically the example provided in the <a href="https://docs.docker.com/engine/examples/dotnetcore/">Docker Documentation</a>. It basically copies the code from the root directory and builds the executables, then moves the executables to a smaller environment with the .NET runtime to run the application.</p><p>On lines 17 and 18 of the Dockerfile, new environment variables are set which will be passed to the application from the container host:</p><pre>ENV MyConfig__Id=&#39;73ce1157-c1b4-4d90-8669-2b33c86d7801&#39;<br>ENV MyConfig__Location=&#39;from Dockerfile&#39;</pre><p>Use the following command to build an image from the Dockerfile:</p><pre>$ docker build -t config-app .</pre><p>Then run the image as a container on port :5000:</p><pre>$ docker run -it -p 5000:5000 config-app</pre><p>The /config response should now show values from the Dockerfile.</p><p>Lastly, a Docker container can be run with variables as command-line arguments to also keep these values separate from source code (or a container repository).</p><p>Run the container again with this command:</p><pre>$ docker run -it -p 5000:5000 \<br>  -e MyConfig__Id=&#39;2021b838-6876-44b9-b123-1f760dc98aaa&#39; \<br>  -e MyConfig__Location=&#39;from Docker CLI&#39; \<br>  config-app</pre><p>…and now you have settings from the command line.</p><h3>Setting the configuration provider hierarchy</h3><p>The default order of configuration providers that get called is logical for most situations, but ASP.NET Core also contains a scaffolding method for overriding the default order.</p><p>In this application, now that there are configuration settings stored in the user secrets file, those will be used over the asppsettings files. We can instead specify that we want appsettings.json to be used instead of user secrets.</p><p>In the sample project, in Program.cs there are five lines commented out that call a method called ConfigureAppConfiguration which takes a configuration builder as its second argument. The builder contains several methods for calling on configuration providers, and the settings from the last method to be called will override any previous settings. If you uncomment the lines you&#39;ll see the following:</p><pre>.ConfigureAppConfiguration((hostContext, config) =&gt;<br>{<br>    config.AddUserSecrets&lt;MyConfig&gt;();<br>    config.AddJsonFile(&quot;appsettings.json&quot;);<br>})</pre><p>Run the application, and you’ll see that the appsettings configuration gets returned. If you change the order of those methods, or add any of the other providers, different configuration settings will be given preference.</p><h3>Conclusion</h3><p>In this project, we saw some of the configuration providers that are available in an ASP.NET Core application and how those settings can be moved around and concealed as the application is deployed to higher environments. This gives several convenient strategies for setting up the application for a variety of deployment types.</p><h3>Further reading</h3><ul><li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1">https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1</a></li><li><a href="https://devblogs.microsoft.com/premier-developer/order-of-precedence-when-configuring-asp-net-core/">https://devblogs.microsoft.com/premier-developer/order-of-precedence-when-configuring-asp-net-core/</a></li><li><a href="https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-3.1&amp;tabs=windows">https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-3.1&amp;tabs=windows</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e98e83963283" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/configuration-in-asp-net-core-explained-e98e83963283">Configuration in ASP.NET Core Explained</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD and Exception Handling With xUnit in ASP.NET Core]]></title>
            <link>https://medium.com/swlh/tdd-and-exception-handling-with-xunit-in-asp-net-core-f9ffe5dde800?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9ffe5dde800</guid>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 22:09:58 GMT</pubDate>
            <atom:updated>2020-08-11T23:19:29.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*iTy3VJUyzk_T0yUjJoC-tg.jpeg" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@nicolasthomas?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Nicolas Thomas</strong></a><strong> on </strong><a href="https://unsplash.com/s/photos/test?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><h3>Introduction and prerequisites</h3><p>In this post, we’re continuing our “walking skeleton” application where we build and deploy a minimal application with an ASP.NET Core WebApi and an Angular client. At this stage, the API is almost ready. We’ve got a controller that accepts a city location, a service that calls the third-party <a href="https://openweathermap.org/api">OpenWeatherMap</a> API to return forecasts for that location, and in the last post we added the xUnit testing framework to describe the API. If you would like to start from the beginning, <a href="https://dev.to/jsheridanwells/starting-up-an-asp-net-core-3-webapi-1lk7">this is the first post</a>.</p><p>The goal of this series, and this application, is to create a bare-bones, testable, and deploy-able web application that can be used as a reference for starting similar projects. In each of these steps, I intend to describe the code we add in detail.</p><p>If you’re starting the tutorial from this post, you can clone the following branch and continue modifying the code from there (note that you will need the <a href="https://dotnet.microsoft.com/download">.NET Core SDK</a> installed on your machine):</p><pre>$ git clone -b 3_adding-tests --single-branch git@github.com:jsheridanwells/WeatherWalkingSkeleton.git<br>$ cd WeatherWalkingSkeleton<br>$ dotnet restore</pre><p>You’ll also need to sign up for and register an <a href="https://openweathermap.org/api">OpenWeatherMap API key</a>. <a href="https://dev.to/jsheridanwells/setting-up-an-n-tier-asp-net-core-app-222d">This previous post</a> contains the steps for doing that.</p><h3>Our TDD process</h3><p>In the previous step, we started with one controller method that called one service method, then we set up a testing library using <a href="https://xunit.net/">xUnit</a> and <a href="https://github.com/moq/moq4">Moq</a>. With our testing framework ready to go, we’ll use unit tests to guide some improvements to our API endpoint that fetches weather forecasts.</p><p><strong>TDD</strong> stands for “Test-Driven Development”, and it’s a technique for ensuring that our code performs according to expectations, documenting the current expectations for code, and using tests to help ensure that changes aren’t breaking prior functionality, especially when deploying code to higher environments. I won’t discuss here the different types of testing, or the differing opinions on testing, but I’ve recently found <a href="https://dev.to/jackmarchant/a-practical-guide-to-test-driven-development-485g">this article</a> which gives an excellent overview of the different software testing strategies and where they can fit into different kinds of projects.</p><p>Our test-driven development is going to follow a <strong>Red</strong>, <strong>Green</strong>, <strong>Refactor</strong> pattern:</p><ol><li><strong>Red</strong>: We will write a test and ensure that it fails. That way we’re sure that our changes are actually bringing about the behavior we want, not some unanticipated side effect.</li><li><strong>Green</strong>: We will modify our methods so that the tests pass.</li><li><strong>Refactor</strong>: We will do any necessary refactoring to our changes so that the code is up to par, while making sure the test still passes.</li></ol><h3>Our changes</h3><p>Right now, our API consists of one endpoint — GET http://localhost:5000/WeatherForecast/:location - that terminates at the WeatherForecastController and calls the Get method. Inside the Get method, the OpenWeatherService.GetFiveDayForecastAsync method is then called which returns a list of five forecasts for the next fifteen hours.</p><p>While manually testing this endpoint with <a href="https://www.postman.com/">Postman</a>, and running our three current unit tests, proves that this indeed happens, our methods are very brittle right now. If an API consumer calls the endpoint without a location, or with a non-existent location, the unexpected result isn’t handled. If we deploy the API to another environment without registering the OpenWeatherMap API key, we need to handle that failure as well in a way that communicates the problem to other developers. Also, the OpenWeatherMap API might itself fail and we need to be able to communicate the source of the problem. At the moment, if anything unexpected happens a long and unhelpful NullReferenceException is returned from the API.</p><p>Let’s refactor the methods to handle the following scenarios:</p><ol><li><strong>One of our users sends a location that OpenWeatherAPI doesn’t recognize:</strong> I would expect this to happen frequently, and it wouldn’t be the result of any fault in the application, so to handle this we’ll send back a helpful message to the user without throwing an exception.</li><li><strong>The OpenWeatherMap API key is invalid:</strong> Right now, the application is running on our local machines with an API key configured. When we deploy to other environments, those servers will also need an API key to run. If the application gets deployed without one, or if the API key expires, we’ll need to make that clear to any developers if OpenWeatherMap returns an unauthorized response.</li><li><strong>OpenWeatherMap returns its own error:</strong> Since OpenWeatherMap is a third party, we cannot guarantee that it always functions within our own application as expected. If for some reason, a request to OpenWeatherMap fails, we need to handle that scenario as well.</li></ol><h3>Testing the service</h3><p>We’ll modify the OpenWeatherService class first. Open the corresponding unit test file: ./WeatherWalkingSkeletonTests/Services_Tests/OpenWeatherService_Tests.cs. Note, that in the previous post, we also created a static fixture class called OpenWeatherResponses that returns three simulated error responses from the OpenWeatherMap API: NotFoundResponse, UnauthorizedResponse, InternalErrorResponse. We&#39;ll use these responses to trigger the errors we could get from the third-party API.</p><p>In OpenWeatherService_Tests add the following tests:</p><pre>[Fact]<br>public async Task Returns_OpenWeatherException_When_Called_With_Bad_Argument()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.NotFoundResponse,<br>        HttpStatusCode.NotFound);<br>    var sut = new OpenWeatherService(opts, clientFactory);</pre><pre>    var result = await Assert.ThrowsAsync&lt;OpenWeatherException&gt;(() =&gt; sut.GetFiveDayForecastAsync(&quot;Westeros&quot;));<br>    Assert.Equal(404, (int)result.StatusCode);<br>}</pre><pre>[Fact]<br>public async Task Returns_OpenWeatherException_When_Unauthorized()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.UnauthorizedResponse,<br>        HttpStatusCode.Unauthorized);<br>    var sut = new OpenWeatherService(opts, clientFactory);</pre><pre>    var result = await Assert.ThrowsAsync&lt;OpenWeatherException&gt;(() =&gt; sut.GetFiveDayForecastAsync(&quot;Chicago&quot;));<br>    Assert.Equal(401, (int)result.StatusCode);<br>}</pre><pre>[Fact]<br>public async Task Returns_OpenWeatherException_On_OpenWeatherInternalError()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.InternalErrorResponse,<br>        HttpStatusCode.InternalServerError);<br>    var sut = new OpenWeatherService(opts, clientFactory);</pre><pre>    var result = await Assert.ThrowsAsync&lt;OpenWeatherException&gt;(() =&gt; sut.GetFiveDayForecastAsync(&quot;New York&quot;));<br>    Assert.Equal(500, (int)result.StatusCode);<br>}</pre><p>The tests follow the basic setup of the previous two tests, but we’ve configured the different possible error responses from the mock API. When OpenWeatherMap returns an unexpected result, we want our service to throw a custom exception called OpenWeatherException. This exception will communicate to the consuming class that the failure came from the third-party API.</p><p>If you run the test using your IDE’s test runner, or using $ dotnet test in the terminal, we see our tests fail. We expected our custom exception and instead got a NullReferenceException since our service can&#39;t yet handle a response that it can&#39;t parse.</p><p>Open ./Api/Services/OpenWeatherService.cs and navigate to the GetFiveDayForecastAsync method. Going through the method line by line, we see the point where the method waits for a response from OpenWeatherMap:</p><pre>var response = await client.GetAsync(url);</pre><p>We’ll check if the response is successful, and if it is then we’ll deserialize the response as we were initially. If it’s any other result, we’ll build and throw an OpenWeatherException so the consuming class can respond accordingly. The <em>if/else</em> block will look like this (I&#39;ll copy the entire method further below):</p><pre>if (response.IsSuccessStatusCode)<br>{<br>    // deserialize and return an OpenWeatherResponse<br>    var json = await response.Content.ReadAsStringAsync();<br>    var openWeatherResponse = JsonSerializer.Deserialize&lt;OpenWeatherResponse&gt;(json);<br>    foreach (var forecast in openWeatherResponse.Forecasts)<br>    {<br>        forecasts.Add(new WeatherForecast<br>        {<br>            Date = new DateTime(forecast.Dt),<br>            Temp = forecast.Temps.Temp,<br>            FeelsLike = forecast.Temps.FeelsLike,<br>            TempMin = forecast.Temps.TempMin,<br>            TempMax = forecast.Temps.TempMax,<br>        });<br>    } </pre><pre>    return forecasts;<br>}<br>else<br>{<br>    // build an exception with information from the third-party API<br>    throw new OpenWeatherException(response.StatusCode, &quot;Error response from OpenWeatherApi: &quot; + response.ReasonPhrase);<br>}</pre><p>The exception will contain the OpenWeatherMap HTTP status code and a simple message, then a consuming class can create logic based on that information.</p><p>Below is what the entire GetFiveDayFirecastAsync method should look like:</p><pre>public async Task&lt;List&lt;WeatherForecast&gt;&gt; GetFiveDayForecastAsync(string location, Unit unit = Unit.Metric)<br>{<br>    string url = BuildOpenWeatherUrl(&quot;forecast&quot;, location, unit);<br>    var forecasts = new List&lt;WeatherForecast&gt;();</pre><pre>    var client = _httpFactory.CreateClient(&quot;OpenWeatherClient&quot;);<br>    var response = await client.GetAsync(url);</pre><pre>    if (response.IsSuccessStatusCode)<br>    {<br>        var json = await response.Content.ReadAsStringAsync();<br>        var openWeatherResponse = JsonSerializer.Deserialize&lt;OpenWeatherResponse&gt;(json);<br>        foreach (var forecast in openWeatherResponse.Forecasts)<br>        {<br>            forecasts.Add(new WeatherForecast<br>            {<br>                Date = new DateTime(forecast.Dt),<br>                Temp = forecast.Temps.Temp,<br>                FeelsLike = forecast.Temps.FeelsLike,<br>                TempMin = forecast.Temps.TempMin,<br>                TempMax = forecast.Temps.TempMax,<br>            });<br>        } </pre><pre>        return forecasts;<br>    }<br>    else<br>    {<br>        throw new OpenWeatherException(response.StatusCode, &quot;Error response from OpenWeatherApi: &quot; + response.ReasonPhrase);<br>    } <br>}</pre><p>Run the tests again and they should all pass. At this point, we’ve done the <em>Red</em> and <em>Green</em> steps of the test process. I’ll leave it up to you to find any opportunities for refactoring this method or letting it go as is.</p><h3>Testing the controller</h3><p>Our service can now graceful indicate if there was a failed response from the OpenWeatherMap API. Now we need our controller communicate these exceptions back to our API’s consuming clients.</p><p>Going back to our original three scenarios, the controller could respond to each in the following ways:</p><ol><li>If OpenWeatherMap couldn’t recognize the location, the controller can return a 400 BadRequest response and let the consumer know the name of the location that failed. Also, if the request is made without a location, we should return a 400 before even calling the service.</li><li>If the OpenWeatherMap returns an Unauthorized response, it&#39;s due to an invalid API key and for this project that&#39;s likely from a bad configuration. We&#39;ll return a 500 Internal Server Error with the message from the OpenWeatherMap API which will indicate if the request was not authorized.</li><li>If there is any other error, we’ll return another 500 response with the message from OpenWeatherMap. Lastly, we&#39;ll also return a 500 response for any other exception that is thrown within the application.</li></ol><p>The responses above lead to three tests that we’ll add to ./Tests/Controllers_Tests/:</p><pre>[Fact]<br>public async Task Returns_400_Result_When_Missing_Location()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.NotFoundResponse);<br>    var service = new OpenWeatherService(opts, clientFactory);<br>    var sut = new WeatherForecastController(new NullLogger&lt;WeatherForecastController&gt;(), service);</pre><pre>    var result = await sut.Get(String.Empty) as ObjectResult;</pre><pre>    Assert.Equal(400, result.StatusCode);<br>}</pre><pre>[Fact]<br>public async Task Returns_BadRequestResult_When_Location_Not_Found()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.NotFoundResponse,<br>        HttpStatusCode.NotFound);<br>    var service = new OpenWeatherService(opts, clientFactory);<br>    var sut = new WeatherForecastController(new NullLogger&lt;WeatherForecastController&gt;(), service);</pre><pre>    var result = await sut.Get(&quot;Westworld&quot;) as ObjectResult;</pre><pre>    Assert.Contains(&quot;not found&quot;, result.Value.ToString());<br>    Assert.Equal(400, result.StatusCode);<br>}</pre><pre>[Fact]<br>public async Task Returns_OpenWeatherException_When_Unauthorized()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.UnauthorizedResponse,<br>        HttpStatusCode.Unauthorized);<br>    var sut = new OpenWeatherService(opts, clientFactory);</pre><pre>    var result = await Assert.ThrowsAsync&lt;OpenWeatherException&gt;(() =&gt; sut.GetFiveDayForecastAsync(&quot;Chicago&quot;));<br>    Assert.Equal(401, (int)result.StatusCode);<br>}</pre><pre>[Fact]<br>public async Task Returns_500_When_Api_Returns_Error()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.UnauthorizedResponse,<br>        HttpStatusCode.Unauthorized);<br>    var service = new OpenWeatherService(opts, clientFactory);<br>    var sut = new WeatherForecastController(new NullLogger&lt;WeatherForecastController&gt;(), service);</pre><pre>    var result = await sut.Get(&quot;Rio de Janeiro&quot;) as ObjectResult;</pre><pre>    Assert.Contains(&quot;Error response from OpenWeatherApi: Unauthorized&quot;, result.Value.ToString());<br>    Assert.Equal(500, result.StatusCode); <br>}</pre><p>If we run them, they should fail.</p><p>We’ll open the class under test in ./Api/Controllers/WeatherForecastController.cs and find the Get() method. Add the following as the first step of the method to check if there is a usable location value with the request:</p><pre>[HttpGet]<br>public async Task&lt;IActionResult&gt; Get(string location, Unit unit = Unit.Metric)<br>{<br>   if (string.IsNullOrEmpty(location))<br>       return BadRequest(&quot;location parameter is missing&quot;);<br>   // [ ... ] <br>}</pre><p>Now, three of the four new tests should be failing.</p><p>For the rest of the tests, we can get them to pass by returning a 400 Bad Request result if OpenWeatherMap can&#39;t find the location, or returning a 500 Internal Server Error for any other reason, along with a helpful message. Also, we can wrap our logic in a <em>try/catch</em> block that will handle an OpenWeatherException as indicated above, then handle any other exception. The updated Get() method can now look like this:</p><pre>[HttpGet]<br>public async Task&lt;IActionResult&gt; Get(string location, Unit unit = Unit.Metric)<br>{<br>    if (string.IsNullOrEmpty(location))<br>        return BadRequest(&quot;location parameter is missing&quot;);<br>    try<br>    {<br>        var forecast = await _weatherService.GetFiveDayForecastAsync(location, unit);<br>        return Ok(forecast);<br>    }<br>    catch (OpenWeatherException e)<br>    {<br>        if (e.StatusCode == HttpStatusCode.NotFound)<br>            return BadRequest($&quot;Location: \&quot;{ location }\&quot; not found.&quot;);<br>        else<br>            return StatusCode(500, e.Message);<br>    }<br>    catch (Exception e)<br>    {<br>        return StatusCode(500, e.Message);<br>    }<br>}</pre><p>Run the tests and we’re successful if we now have nine passing tests in the collection. As before, if you would like to experiment with other ways to handle exceptions from the OpenWeatherService, you can now refactor the method secured with its corresponding tests.</p><h3>Conclusion</h3><p>In this tutorial, we started with a project with an API endpoint that could handle a “happy path,” but could not meaningfully handle exceptions. We came up with three possible exception scenarios, then used test-driven development for describing the desired behavior for our classes, making changes until the tests passed. We now have a more robust example ASP.NET Core project. In the next tutorials, we will Docker-ize the API to support complimentary development, then scaffold an Angular project to serve as a client.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9ffe5dde800" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/tdd-and-exception-handling-with-xunit-in-asp-net-core-f9ffe5dde800">TDD and Exception Handling With xUnit in ASP.NET Core</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing an ASP.NET Core Service With xUnit]]></title>
            <link>https://medium.com/swlh/testing-an-asp-net-core-service-with-xunit-f18225d9b22a?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18225d9b22a</guid>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 21:06:02 GMT</pubDate>
            <atom:updated>2020-08-05T16:31:49.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*8UtvT7V8iPo-PFnMfXXXbw.jpeg" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@moonshadowpress?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Joyce McCown</strong></a><strong> on </strong><a href="https://unsplash.com/s/photos/test-tubes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><h3>Introduction and prerequisites</h3><p>This post is part of an ongoing series where we build a <a href="https://whatis.techtarget.com/definition/walking-skeleton#:~:text=A%20walking%20skeleton%2C%20in%20a,basic%20components%20of%20the%20system.">“walking skeleton”</a> application using ASP.NET Core and Angular as well as other technologies for deployment and testing. By now, our application is a minimally functional web API that organizes and returns weather data from a location. In this post, we will use <a href="https://xunit.net/">xUnit</a> to test how a service handles calls to a third-party API, then how a controller responds to a successful response. In the next post, we’ll then use those tests to scaffold some exception handling that’s missing from our classes right now. As in other posts, the aim of this article is to go through the steps with detailed explanations.</p><p>If you would like to start from the beginning, <a href="https://dev.to/jsheridanwells/starting-up-an-asp-net-core-3-webapi-1lk7">this post</a> will introduce the project and walk you up to this point. If you’re just here for a walkthrough of testing with xUnit, then you can:</p><ol><li>Begin by cloning the project up to this point and cd-ing into it:</li></ol><pre>$ git clone -b 2_adding-async --single-branch git@github.com:jsheridanwells/WeatherWalkingSkeleton.git<br>$ cd WeatherWalkingSkeleton</pre><ol><li>Register for an <a href="https://openweathermap.org/api">OpenWeatherMap API key</a>,</li><li>And add the API key to the secrets store for this project:</li></ol><pre>$ dotnet user-secrets set &quot;OpenWeather:ApiKey&quot; &quot;&lt;YOUR-API-KEY&gt;&quot; --project ./Api/WeatherWalkingSkeleton.csproj</pre><ol><li>Test that the web API is working properly up to now:</li></ol><pre>$ dotnet restore<br>$ dotnet run --project Api/WeatherWalkingSkeleton.csproj</pre><p>… and in another terminal, make a request to make sure a result comes out:</p><pre>$ curl -k <a href="https://localhost:5001/weatherforecast?location=detroit">https://localhost:5001/weatherforecast?location=detroit</a></pre><p>If you get what looks like an array of weather forecasts, then you are good to go.</p><h3>Testing Goals</h3><p>For this stage of the project, we will add some tests for two of the classes that we’ve built so far: the OpenWeatherService and the WeatherForecastController. This is to establish a pattern of tests that describe the code, and as the application grows in complexity, we&#39;ll be sure new changes won&#39;t break prior functionality.</p><p>I’ve read lots of opinions on software testing from engineers much more experienced than me — from strictly adhering to test-driven development to strategies that might be more pragmatic. The strategy I’ve decided on is to test how the OpenWeatherService responds to different possible responses from the third-party API. Since we do not want to call the actual OpenWeatherMap API, we will set up a substitute class where we can simulate the responses. After writing tests for the service, we&#39;ll then set up the service with the WeatherForecastController to test that data is returned properly from the API. From there, we&#39;ll have a small set of tests that describe the classes and can run in the future to keep any new work from breaking the prior work.</p><p>To the steps to get there are:</p><ol><li>Set up our test project with the <a href="https://xunit.net/">xUnit</a> and <a href="https://github.com/moq/moq4">Moq</a> libraries.</li><li>Write tests to describe the classes’ current functionality.</li></ol><h3>Creating a test project</h3><p>The <a href="https://docs.microsoft.com/en-us/dotnet/core/tools/">dotnet CLI</a> contains a template for adding a xUnit test project, as well as templates for the nUnit and MSTest libraries. Let’s create that project:</p><pre>$ dotnet new xunit -o Tests -n WeatherWalkingSkeleton.Tests</pre><p>Next, we add the test project to the WeatherWalkingSkeleton solution:</p><pre>$ dotnet sln WeatherWalkingSkeleton.sln add ./Tests/WeatherWalkingSkeleton.Tests.csproj</pre><p>Then, to see that the tests are discoverable, run:</p><pre>$ dotnet test</pre><p>If everything is working alright, you’ll see the results of one passing fake test.</p><p>If you are using Visual Studio, there is a built-in test explorer that will provide a UI for running and debugging tests. You can get a similar set of functionality with VS Code using the <a href="https://marketplace.visualstudio.com/items?itemName=formulahendry.dotnet-test-explorer">.NET Core Test Explorer</a> plugin. Otherwise, running $ dotnet test from the command line will suffice for this tutorial.</p><p>We need to add a reference to our test project so that it can access the classes from the API library under test:</p><pre>$ dotnet add Tests/WeatherWalkingSkeleton.Tests.csproj reference Api/WeatherWalkingSkeleton.csproj</pre><p>Lastly, we’ll add a few directories and test classes to the testing library. It will take on a similar structure to the API project so that it will be easier to compare a class to its tests. Let’s add directories for any controller and service classes:</p><pre>$ mkdir ./Tests/Controllers_Tests ./Tests/Services_Tests</pre><p>Then we’ll add the test classes. You can either add the files via command line or scaffold a class with the IDE you’re using:</p><pre>$ touch ./Tests/{/Controllers_Tests/WeatherForecastController_Tests.cs,/Services_Tests/OpenWeatherService_Tests.cs}</pre><p>We’ll also create an Infrastructure directory for any fixtures or utilities needed to support the test classes:</p><pre>$ mkdir ./Tests/Infrastructure</pre><p>Lastly, the fake example test can be removed:</p><pre>$ rm ./Tests/UnitTest1.cs</pre><h3>Setting up test fixtures</h3><p>The OpenWeatherService will be the trickier class to test because it creates an HttpClient object to make calls to a third-party API. We want to test how it handles different kinds of responses from the API, but we don&#39;t want to actually make those requests. We&#39;ll have to simulate the kinds of responses the API might return. Also, our service class uses an IOptions object in order to extract a secret API key to use. We don&#39;t want any API keys to appear in our code, and in fact it&#39;s not really important whether we have a real API key or not, so we&#39;ll have to create a service to test with an alternate IOptions object.</p><p>So here’s a strategy for describing and testing the OpenWeatherService:</p><ol><li>Create an empty IOptions&lt;OpenWeather&gt; object to inject into the service.</li><li>Create a mock HttpClient that can return simulated responses.</li><li>Handle the “happy path” scenario — how does the service return a successful response from the API?</li></ol><h3>1. Setting up an Options Builder</h3><p>In the Infrastructure directory, add a class called OptionsBuilder.cs. This will be a static class, and so far all we need it to do is to return an Options object with one of the OpenWeatherMap configuration objects as its value:</p><pre>using Microsoft.Extensions.Options;<br>using WeatherWalkingSkeleton.Config;</pre><pre>namespace WeatherWalkingSkeleton.Tests.Infrastructure<br>{<br>    public static class OptionsBuilder<br>    {<br>        public static IOptions&lt;OpenWeather&gt; OpenWeatherConfig()<br>        {<br>            return Options.Create&lt;OpenWeather&gt;(new OpenWeather { ApiKey = &quot;00000&quot;});<br>        }<br>    }<br>}</pre><p>Not much happening here, but we’ve got a passable object to build a test OpenWeatherService</p><h3>2. Setting up an HttpClient Builder</h3><p>This one is going to be more involved. Our service gets instantiated with an IHttpClientFactory and we call a CreateClient method from the object to get an HttpClient. This strategy is a workaround because we cannot mock an HttpClient directly.</p><p>To assist in mocking the objects, we’ll add a very common Nuget package called Moq:</p><pre>$ dotnet add Tests/WeatherWalkingSkeleton.Tests.csproj package Moq</pre><p>In Infrastructure, create a ClientBuilder.cs class, also a static class. It will have a static method called OpenWeatherClientFactory. In order to make the method more versatile, we&#39;ll give it two arguments: StringContent content will be the simulated response from the API and HttpStatusCode statusCode will be HTTP response code, e.g. 200, 400, 401. I&#39;ll paste the entire class directly below, then explain each part:</p><pre>using System.Net;<br>using System.Net.Http;<br>using System.Threading;<br>using System.Threading.Tasks;<br>using Moq;<br>using Moq.Protected;</pre><pre>namespace WeatherWalkingSkeleton.Tests.Infrastructure<br>{<br>    public static class ClientBuilder<br>    {<br>        public static IHttpClientFactory OpenWeatherClientFactory(StringContent content, HttpStatusCode statusCode = HttpStatusCode.OK)<br>        {<br>            var handler = new Mock&lt;HttpMessageHandler&gt;();<br>            handler.Protected()<br>                .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(<br>                    &quot;SendAsync&quot;,<br>                    ItExpr.IsAny&lt;HttpRequestMessage&gt;(),<br>                    ItExpr.IsAny&lt;CancellationToken&gt;()<br>                )<br>                .ReturnsAsync(new HttpResponseMessage<br>                {<br>                    StatusCode = statusCode,<br>                    Content = content<br>                });<br>            var client = new HttpClient(handler.Object);<br>            var clientFactory = new Mock&lt;IHttpClientFactory&gt;();<br>            clientFactory.Setup(_ =&gt; _.CreateClient(It.IsAny&lt;string&gt;()))<br>                .Returns(client);<br>            return clientFactory.Object;<br>        }<br>    }<br>}</pre><p>HttpClient uses an object internally called HttpMessageHandler to make the actual HTTP request. We will mock it using the Moq library:</p><pre>var handler = new Mock&lt;HttpMessageHandler&gt;();</pre><p>The handler has a method called SendAsync that is called to send the request, so we will use Moq to set up the response that we want:</p><pre>handler.Protected()<br>.Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(<br>    &quot;SendAsync&quot;,<br>    ItExpr.IsAny&lt;HttpRequestMessage&gt;(),<br>    ItExpr.IsAny&lt;CancellationToken&gt;()<br>)<br>.ReturnsAsync(new HttpResponseMessage<br>{<br>    StatusCode = statusCode,<br>    Content = content<br>});</pre><p>With our fake message handler, we’ll create a real HttpClient object:</p><pre>var client = new HttpClient(handler.Object);</pre><p>And then we’ll create a mock IHttpClientFactory that returns our HttpClient</p><pre>var client = new HttpClient(handler.Object);<br>var clientFactory = new Mock&lt;IHttpClientFactory&gt;();<br>clientFactory.Setup(_ =&gt; _.CreateClient(It.IsAny&lt;string&gt;()))<br>    .Returns(client);<br>return clientFactory.Object;</pre><h3>3. Generating Controlled Third-Party API Responses</h3><p>The last piece of infrastructure we’ll need is a static class that can return some canned responses that sort of look like the responses that would come back from the OpenWeatherMap API. From testing the API in Postman, we can see that a successful response returns an array of objects that resemble the project’s WeatherForecast class with an HTTP status of 200.</p><p>We can also predict a few other scenarios:</p><ol><li>If the resource is called with a missing or invalid API key, we get a 401 status with “Invalid Api key”.</li><li>If the resource is called without a valid city name, we get a 404 status with “city not found”.</li><li>And, I can’t be sure from testing what an error from the third-party server looks like, based on convention we’ll guess that it’s a 500 HTTP status with “Internal Error.” as the message.</li></ol><p>Add a file to the ./Tests/Infrastructure directory called OpenWeatherResponses.cs. Then, paste the following code which will create the canned responses for our mock HTTP factory to return:</p><pre>using System.Collections.Generic;<br>using System.Net.Http;<br>using System.Text.Json;<br>using WeatherWalkingSkeleton.Models;</pre><pre>namespace WeatherWalkingSkeleton.Tests.Infrastructure<br>{<br>    public static class OpenWeatherResponses<br>    {<br>        public static StringContent OkResponse =&gt; BuildOkResponse();<br>        public static StringContent UnauthorizedResponse =&gt; BuildUnauthorizedResponse();<br>        public static StringContent NotFoundResponse =&gt; BuildNotFoundResponse();<br>        public static StringContent InternalErrorResponse =&gt; BuildInternalErrorResponse();</pre><pre>        private static StringContent BuildOkResponse()<br>        {<br>            var response = new OpenWeatherResponse<br>            {<br>                Forecasts = new List&lt;Forecast&gt;<br>                {<br>                    new Forecast{ Dt = 1594155600, Temps = new Temps { Temp = (decimal)32.93 } }<br>                }<br>            };<br>            var json = JsonSerializer.Serialize(response);<br>            return new StringContent(json);<br>        }</pre><pre>        private static StringContent BuildUnauthorizedResponse()<br>        {<br>            var json = JsonSerializer.Serialize(new { Cod = 401, Message = &quot;Invalid Api key.&quot; });<br>            return new StringContent(json);<br>        }</pre><pre>        private static StringContent BuildNotFoundResponse()<br>        {<br>            var json = JsonSerializer.Serialize(new { Cod = 404, Message = &quot;city not found&quot; });<br>            return new StringContent(json);<br>        }</pre><pre>        private static StringContent BuildInternalErrorResponse()<br>        {<br>            var json = JsonSerializer.Serialize(new {Cod = 500, Message = &quot;Internal Error.&quot;});<br>            return new StringContent(json);<br>        }<br>    }<br>}</pre><h3>Testing the Service</h3><p>Now that we can control the response we get when pretending to call the OpenWeatherMap API, we’ll set up some tests to describe the OpenWeatherService.</p><p>So far, the class contains one method: GetFiveDayForecastAsync. We expect it to return a list of WeatherForecast objects. In the future, we&#39;ll need to update this method to handle any errors that get returned from the API, but for now the test will just describe what the method is <em>supposed</em> to do. Also, note that the class contains a private method called BuildOpenWeatherUrl. Since it&#39;s a private method, we can&#39;t test it in isolation, but since we know that GetFiveDayForecastAsync depends on it, any failures from the private method will be indicated when testing the public method.</p><p>Here are a couple of responses that we can expect from GetFiveDayForecastAsync:</p><ol><li>It will return a list of WeatherForecast objects, no other objects.</li><li>The Date and the Temp properties that come from the API response will be the same when the WeatherForecast list is created.</li></ol><p>Add a test file in the .Tests/Services_Tests directory:</p><pre>$ touch ./Tests/Services_Tests/OpenWeatherService_Tests.cs</pre><p>The class, with all of the using statements should start like this:</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Net;<br>using System.Threading.Tasks;<br>using WeatherWalkingSkeleton.Infrastructure;<br>using WeatherWalkingSkeleton.Models;<br>using WeatherWalkingSkeleton.Tests.Infrastructure;<br>using Xunit;</pre><pre>namespace WeatherWalkingSkeleton.Services<br>{<br>    public class OpenWeatherService_Tests<br>    {</pre><pre>    }<br>}</pre><p>Inside the service, let’s add two methods for each of the descriptions we want to provide. Here are the methods:</p><pre>[Fact]<br>public async Task Returns_A_WeatherForecast()<br>{</pre><pre>}</pre><pre>[Fact]<br>public async Task Returns_Expected_Values_From_the_Api()<br>{</pre><pre>}</pre><p>Note that the [Fact] annotation allows a test explorer to find and run any test methods.</p><p>Now we’ll add code to the first method. Since in each test, we’ll need to create a OpenWeatherService, we&#39;ll generate IOptions&lt;OpenWeather&gt; and IHttpClientFactory objects using the fixtures created above, then create an OpenWeatherService named sut for &quot;system under test&quot;. With the service instantiated, we&#39;ll call GetFiveDayForecastAsync. On the last line, the Assert class from xUnit is used to test that the method is returning the type of object that we expect:</p><pre>[Fact]<br>public async Task Returns_A_WeatherForecast()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.OkResponse);<br>    var sut = new OpenWeatherService(opts, clientFactory);</pre><pre>    var result = await sut.GetFiveDayForecastAsync(&quot;Chicago&quot;);</pre><pre>    Assert.IsType&lt;List&lt;WeatherForecast&gt;&gt;(result);<br>}</pre><p>The second test is set up exactly the same way, but in this test we’re seeing if we find the same Date and Temp values that we loaded OpenWeatherResponses.BuildOkResponse() with earlier:</p><pre>[Fact]<br>public async Task Returns_Expected_Values_From_the_Api()<br>{<br>    var opts = OptionsBuilder.OpenWeatherConfig();<br>    var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.OkResponse);<br>    var sut = new OpenWeatherService(opts, clientFactory);</pre><pre>    var result = await sut.GetFiveDayForecastAsync(&quot;Chicago&quot;);</pre><pre>    Assert.Equal(new DateTime(1594155600), result[0].Date);<br>    Assert.Equal((decimal)32.93, result[0].Temp);<br>}</pre><p>Now run the tests in the IDE test explorer, or in the command line terminal ($ dotnet test) to make sure they pass.</p><h3>Testing the Controller</h3><p>Now we’ll add a file for running some controller tests:</p><pre>$ touch ./Tests/Services_Tests/WeatherForecastController_Tests.cs</pre><p>Just like the service, so far our WeatherForecastController that consumes the OpenWeatherService just has one method called Get for returning the result of the service. While our previous tests were strictly isolated unit tests - the API and the HTTP client were mocked - I&#39;d like the controller tests to be more of an <em>integration</em> test: I&#39;d like to know how it responds to different results from the OpenWeatherService that it depends on. If we make a change to the OpenWeatherService that could break the WeatherForecastController, we wouldn&#39;t know it if we were mocking the service in these tests. So in our tests, we&#39;ll build an OpenWeatherService with the API response that we expect, then build the controller with that.</p><p>Our WeatherForecastController requires an ILogger&lt;WeatherForecastController&gt; in the constructor. Luckily, the Microsoft.Extensions.Logging library that it the interface comes from also has a class called NullLogger&lt;T&gt; that lets us just pass in an empty logger since logging has nothing to do with the functionality that we&#39;re testing. The setup for creating the controller as our system under test is as follows (Note, I&#39;ll copy in the full method further down):</p><pre>var opts = OptionsBuilder.OpenWeatherConfig();<br>var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.OkResponse);<br>var service = new OpenWeatherService(opts, clientFactory);<br>var sut = new WeatherForecastController(new NullLogger&lt;WeatherForecastController&gt;(), service);</pre><p>After the controller is created we will await the result and convert it to an OkObjectResult that will contain the API response to evaluate:</p><pre>var result = await sut.Get(&quot;Chicago&quot;) as OkObjectResult;</pre><p>Lastly, we’ll make sure that a successful response from the OpenWeatherService results in a &quot;success&quot; response from the controller, along with the List&lt;WeatherForecast&gt; object that we&#39;re expecting:</p><pre>Assert.IsType&lt;List&lt;WeatherForecast&gt;&gt;(result.Value);<br>Assert.Equal(200, result.StatusCode);</pre><p>Altogether, the WeatherForecastController_Tests class should look like this:</p><pre>using System.Collections.Generic;<br>using System.Net;<br>using System.Threading.Tasks;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.Extensions.Logging.Abstractions;<br>using WeatherWalkingSkeleton.Controllers;<br>using WeatherWalkingSkeleton.Models;<br>using WeatherWalkingSkeleton.Services;<br>using WeatherWalkingSkeleton.Tests.Infrastructure;<br>using Xunit;</pre><pre>namespace WeatherWalkingSkeleton.Tests.Controllers_Tests<br>{<br>    public class WeatherForecastController_Tests<br>    {<br>        [Fact]<br>        public async Task Returns_OkResult_With_WeatherForecast()<br>        {<br>            var opts = OptionsBuilder.OpenWeatherConfig();<br>            var clientFactory = ClientBuilder.OpenWeatherClientFactory(OpenWeatherResponses.OkResponse);<br>            var service = new OpenWeatherService(opts, clientFactory);<br>            var sut = new WeatherForecastController(new NullLogger&lt;WeatherForecastController&gt;(), service);</pre><pre>            var result = await sut.Get(&quot;Chicago&quot;) as OkObjectResult;</pre><pre>            Assert.IsType&lt;List&lt;WeatherForecast&gt;&gt;(result.Value);<br>            Assert.Equal(200, result.StatusCode);<br>        }<br>    }<br>}</pre><p>Run the tests again, and we should have three total successful tests.</p><h3>Conclusion</h3><p>That’s far enough for now. From this tutorial, we were able to install a test library for an ASP.NET Core WebApi project. We also created some initial infrastructure to control the dependencies that we are not testing as well as create a mock version of a third-party API so that we can control the different responses it might give. We used this to evaluate successful responses from our service, then to evaluate the same responses in the controller that consumes the service.</p><p>In the next tutorial, we’ll start a <a href="https://www.agilealliance.org/glossary/tdd/#q=~(infinite~false~filters~(postType~(~&#39;page~&#39;post~&#39;aa_book~&#39;aa_event_session~&#39;aa_experience_report~&#39;aa_glossary~&#39;aa_research_paper~&#39;aa_video)~tags~(~&#39;tdd))~searchTerm~&#39;~sort~false~sortDirection~&#39;asc~page~1)">TDD</a> process for adding exception handling functionality to the controller and service methods.</p><h3>References</h3><p>These posts proved especially helpful in figuring out how to use HttpClient in tests.</p><ul><li><a href="https://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/">How to mock HttpClient in your .NET / C# unit tests</a></li><li><a href="https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore">An Introduction ot HttpClientFactory</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18225d9b22a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/testing-an-asp-net-core-service-with-xunit-f18225d9b22a">Testing an ASP.NET Core Service With xUnit</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consuming third-party APIs in ASP.NET Core]]></title>
            <link>https://medium.com/swlh/consuming-third-party-apis-in-asp-net-core-9ddbfd50728a?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ddbfd50728a</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 20:33:31 GMT</pubDate>
            <atom:updated>2020-07-01T00:19:18.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*lNjyqT8rBrhWBz8DumH8jA.jpeg" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@wimvanteinde?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Wim van ‘t Einde</strong></a><strong> on </strong><a href="https://unsplash.com/s/photos/three-layers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><h3>Introduction</h3><p>This post is the second phase of work on a <a href="https://whatis.techtarget.com/definition/walking-skeleton#:~:text=A%20walking%20skeleton%2C%20in%20a,basic%20components%20of%20the%20system.">walking skeleton</a> application, and part of a series where we build out and deploy a minimal-but-functional web application built with the ASP.NET Core and Angular frameworks. In the <a href="https://dev.to/jsheridanwells/starting-up-an-asp-net-core-3-webapi-1lk7">introductory post</a>, I explained the intent of this series in more detail and set up and toured the boilerplate code for an ASP.NET Core WebApi application. In the <a href="https://dev.to/jsheridanwells/setting-up-an-n-tier-asp-net-core-app-222d">next post</a>, we made some initial configuration, and built out a controller and a service to be able to return data from a third-party API. Here, we will make our service a little more robust. We will refactor this service class to make it more testable and to take advantage of async features in C#.</p><h3>Prequisites</h3><p>This article will be a continuation of <a href="https://dev.to/jsheridanwells/starting-up-an-asp-net-core-3-webapi-1lk7">Part 0</a> and <a href="https://dev.to/jsheridanwells/setting-up-an-n-tier-asp-net-core-app-222d">Part 1</a> of this series. My goal for this series is to walk through a sample application while explaining the <em>hows</em> and <em>whys</em> of the ASP.NET Core framework in detail. If you are looking for a solution for consuming a third-party API in an ASP.NET Core application, going through this tutorial on its own should suffice. If you are looking for a more fundamental understanding of the framework, <a href="https://dev.to/jsheridanwells/starting-up-an-asp-net-core-3-webapi-1lk7">starting from the beginning</a> may be a better bet.</p><p>For this tutorial, you will need:</p><ol><li>Git, Postman, the .NET Core SDK, and an IDE or text editor that can work comfortably with C# code. Visual Studio Code with <a href="https://code.visualstudio.com/docs/languages/csharp">these plugins</a> is a serviceable free setup. <a href="https://dev.to/jsheridanwells/starting-up-an-asp-net-core-3-webapi-1lk7">Part 0</a> of this series goes through this setup in more detail.</li><li>An <a href="https://openweathermap.org/api">OpenWeatherMap</a> API key. This is the third-party API that we’ll be consuming in this example application. in <a href="https://dev.to/jsheridanwells/setting-up-an-n-tier-asp-net-core-app-222d">Part 1</a>, I walk through getting the API key and using the User Secrets Manager in .NET Core to store the key in a file system.</li><li>The starting point for the example code used in this application. You can clone the starting branch for this repository with this command:</li></ol><pre>$ git clone -b 1_aspnetcore_webapi_setup --single-branch git@github.com:jsheridanwells/WeatherWalkingSkeleton.git</pre><p>As in the previous articles, if this is your first time building a web API, or if you need an introduction to how to go about it in ASP.NET Core, this article will provide a detailed explanation of the steps and the features of this particular framework. I won’t go into the C# language syntax, but the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/intro-to-csharp/">Microsoft documentation</a> has a great primer on the language itself.</p><h3>Initial Walkthrough</h3><p>If you’ve cloned the application from our starting point in the previous section, and if you’ve registered an API key for the OpenWeatherMap service, from the root directory of the project, use these steps to verify that the application is running:</p><pre>$ dotnet run --project Api/WeatherWalkingSkeleton.csproj</pre><p>If the output is error-message free, similar to the following…</p><pre>info: Microsoft.Hosting.Lifetime[0]<br>      Now listening on: https://localhost:5001<br>info: Microsoft.Hosting.Lifetime[0]<br>      Now listening on: http://localhost:5000<br>info: Microsoft.Hosting.Lifetime[0]<br>      Application started. Press Ctrl+C to shut down.<br>info: Microsoft.Hosting.Lifetime[0]<br>      Hosting environment: Development<br>info: Microsoft.Hosting.Lifetime[0]<br>      Content root path: /Users/YOU-USER-NAME/workspace/projects/Portfolio/BlogTutorials/WeatherWalkingSkeleton/Api</pre><p>… then the application is working properly.</p><p>Open Postman, and make a GET request to this URL : https://localhost:5001/WeatherForecast?location=chicago. (You can substitute any other city for Chicago).</p><p>If the response is an array of temperature forecast objects, then your OpenWeatherMap API key is configured properly. If not, you may want to go back to <a href="https://dev.to/jsheridanwells/setting-up-an-n-tier-asp-net-core-app-222dv">Part 1</a> of this series to check over the User Secrets Manager setup. Alternately, if you just want to hard-code the API key and skip saving it to your file system, I’ll show you the place to do that further below.</p><p>The file that we will be refactoring the most in this tutorial is located at ./Api/Services/OpenWeatherService.cs. Open that now in an IDE or text editor. It contains a method called GetFiveDayForecast:</p><pre>public List&lt;WeatherForecast&gt; GetFiveDayForecast(string location, Unit unit = Unit.Metric)<br>{<br>    string url = $&quot;https://api.openweathermap.org/data/2.5/forecast?q={ location }&amp;appid={ _openWeatherConfig.ApiKey }&amp;units={ unit }&quot;;<br>    var forecasts = new List&lt;WeatherForecast&gt;();<br>    using (HttpClient client = new HttpClient())<br>    {<br>        var response = client.GetAsync(url).Result;<br>        var json = response.Content.ReadAsStringAsync().Result;<br>        var openWeatherResponse = JsonSerializer.Deserialize&lt;OpenWeatherResponse&gt;(json);<br>        foreach (var forecast in openWeatherResponse.Forecasts)<br>        {<br>            forecasts.Add(new WeatherForecast<br>            {<br>                Date = new DateTime(forecast.Dt),<br>                Temp = forecast.Temps.Temp,<br>                FeelsLike = forecast.Temps.FeelsLike,<br>                TempMin = forecast.Temps.TempMin,<br>                TempMax = forecast.Temps.TempMax,<br>            });<br>        }<br>    }</pre><pre>    return forecasts;<br>}</pre><ol><li>The method takes in the name of a location and a unit of measurement, defaulting to metric.</li><li>A URL is built using these parameters and an API key. <strong>Note that if you want to skip the configuration step from the previous tutorial, you can copy paste your OpenWeatherMap API key here, and the method should work.</strong></li><li>An HttpClient object is built to return the data.</li><li>HttpClient makes the call to the API, reads the result as a JSON string, then deserializes the desired values.</li><li>Finally, a list of weather forecasts is built and returned.</li></ol><p>This method will work as is, but it has a few code smells. First, the service class will be difficult to unit test because HttpClient is instantiated directly in the method. A test that triggers the method will make an actual call to the API which is undesirable for several reasons including inconsistent test results if the API happens to fail. We can take advantage of <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1">dependency injection</a> to make the HttpClient object more versatile.</p><p>Another problem is that we are calling two asynchronous methods from HttpClient, but we are still using them synchronously. As written, GetAsync and ReadAsStringAsync will block the thread that is running this process until the two methods resolve. For what we&#39;re doing right now, this doesn&#39;t make a difference, but if we imagine a more complex version of this method - one that fetches data from several sources or processes large amounts of data - then the results of this method would not be performant nor consistent. We want to change our method to take advantage of asynchronous features that are available in C#.</p><p>Finally, while not necessarily a code smell, we can have the URL built by another method. This could make the URL-building <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>-er and more versatile as other methods get added to this class in the future.</p><h3>Creating a URL-builder</h3><p>Writing a separate URL method will be the easiest step in refactoring. When we break down the structure of the OpenWeatherMap url, its parts are primarily domain + version number + a resource + query parameters + the API key. Let&#39;s create a method where we can at least specify the resource and the query parameters when requesting a URL.</p><p>Below the GetFiveDayForecast method, add the following private method:</p><pre>private string BuildOpenWeatherUrl(string resource, string location, Unit unit)<br>{<br>    return $&quot;https://api.openweathermap.org/data/2.5/{resource}&quot; +<br>           $&quot;?appid={_openWeatherConfig.ApiKey}&quot; +<br>           $&quot;&amp;q={location}&quot; +<br>           $&quot;&amp;units={unit}&quot;;<br>}</pre><p>And in GetFiveDayForecast, change the hard-coded url to the result of the private method:</p><pre>public async Task&lt;List&lt;WeatherForecast&gt;&gt; GetFiveDayForecastAsync(string location, Unit unit = Unit.Metric)<br>{<br>    string url = BuildOpenWeatherUrl(&quot;forecast&quot;, location, unit);<br>    // [...]<br>}</pre><p>Nothing major there, but at least it moves a big ugly string out of the method and makes it more readable.</p><h3>Injecting IHttpClientFactory</h3><p>For us to unit test our OpenWeatherMapService class in the future, it would be better to create a mock of HttpClient that will return canned responses that look like OpenWeatherMap responses without actually using the real API. We want our tests to describe the service independently of the API.</p><p>However, while HttpClient is a very common way to make HTTP requests, it is an older .NET library and as such it is not really designed to be easily mocked in unit tests. Luckily, .NET Core provides us with an interface called IHttpClientFactory which solves a number of issues with making a WebApi application more stable and scalable. Specifically for us, IHttpFactory will create an HttpClient for us instead of us directly instantiating it in our method. That way, in future unit tests, we can easily inject a pseudo-HttpClient.</p><p>First, we will add IHttpClientFactory as one of the service&#39;s class constructor parameters and hold it as a private attribute:</p><pre>public class OpenWeatherService : IOpenWeatherService<br>{<br>    private readonly OpenWeather _openWeatherConfig;<br>    private readonly IHttpClientFactory _httpFactory;</pre><pre>    public OpenWeatherService(IOptions&lt;OpenWeather&gt; opts, IHttpClientFactory httpFactory)<br>    {<br>        _openWeatherConfig = opts.Value;<br>        _httpFactory = httpFactory;<br>    }<br>    // [...]<br>}</pre><p>Before moving on, we’ll need to declare an instance of an IHttpClientFactory class in our Startup class. From the root directory, open ./Api/Startup.cs and add the following line to the ConfigureServices method:</p><pre>public class Startup<br>{<br>   // [...] <br>    public void ConfigureServices(IServiceCollection services)<br>    {<br>        // [...] <br>        services.AddHttpClient();<br>    }<br>}</pre><p>The <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1">documentation</a> describes a number of possibilities for setting up an IHttpClientFactory, but for now this will do what our code is already doing.</p><p>Back to the OpenWeatherService, we&#39;ll replace the code in the block that starts with using (HttpClient client = new HttpClient()) with the following:</p><pre>var client = _httpFactory.CreateClient();<br>var response = await client.GetAsync(url);<br>var json = await response.Content.ReadAsStringAsync();<br>var openWeatherResponse = JsonSerializer.Deserialize&lt;OpenWeatherResponse&gt;(json);<br>foreach (var forecast in openWeatherResponse.Forecasts)<br>{<br>    forecasts.Add(new WeatherForecast<br>    {<br>        Date = new DateTime(forecast.Dt),<br>        Temp = forecast.Temps.Temp,<br>        FeelsLike = forecast.Temps.FeelsLike,<br>        TempMin = forecast.Temps.TempMin,<br>        TempMax = forecast.Temps.TempMax,<br>    });<br>}</pre><p>Now we’ve separated creating the HttpClient object from our own class.</p><p>At this point, the method will show errors because of the lines starting with var response and var json. WE have added the await keyword so that response and json represent the result of the two tasks that were called. In order to run this properly, we&#39;ll need to convert GetFiveDayWeatherForecast to an async method.</p><h3>Converting to async</h3><p>We’re halfway through refactoring, but we’ve still got our more complicated tasks ahead. Now we’ll convert GetFiveDayWeatherForecast so that it runs asynchronously.</p><p>Normally a program written in C# runs sequentially, line by line, and each subsequent step waits for the preceding step. However, some operations that require separate processes — eg. reading from a database, reading from a file system — will cause the process that is executing to stop until other operations can finish. C# provides us with features to better manage these processes so that some might run in parallel and the results returned in order. <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/">This article</a> provides a detailed description of async methods in C# that is well worth reading. In C#, asynchronous methods are typically managed as tasks that return a result after completion. We use the await keyword to make sure that we have the result of the process before performing any logic on it.</p><p>To transform GetGiveDayWeatherForecast into an async method, first we need to change its return type from a list of weather forecasts, to a <em>task</em> that will result in this list. While, we&#39;re at it, we&#39;ll rename the method GetFiveDayWeatherForecastAsync which is a convention in C# that indicates to anyone writing a consuming class that the method can be await-ed. We&#39;ll change the method in the IOpenWeatherService interface and the OpenWeatherService class.</p><pre>public interface IOpenWeatherService<br>{<br>    Task&lt;List&lt;WeatherForecast&gt;&gt; GetFiveDayForecastAsync(string location, Unit unit = Unit.Metric);<br>}</pre><pre>public class OpenWeatherService : IOpenWeatherService<br>{<br>    // [...]<br>    public async Task&lt;List&lt;WeatherForecast&gt;&gt; GetFiveDayForecastAsync(string location, Unit unit = Unit.Metric)<br>    // [...]<br>}</pre><p>We’ll also need to change the reference to the method in the WeatherForecastController class located in ./Api/Controllers/WeatherForecastController.cs. Since we will be <em>awaiting</em> the result of GetFiveDayForecast, the controller method has to be async as well:</p><pre>public class WeatherForecastController : ControllerBase<br>{<br>    // [...]<br>    [HttpGet]<br>    public async Task&lt;IActionResult&gt; Get(string location, Unit unit = Unit.Metric)<br>    {<br>        var forecast = await _weatherService.GetFiveDayForecastAsync(location, unit);<br>        return Ok(forecast);<br>    }<br>}</pre><p>You may want to compile the code ($ dotnet build) to make sure these changes are correct before moving on.</p><p>Back in OpenWeatherService, we can add await to the two async methods that are called from HttpClient:</p><pre>public async Task&lt;List&lt;WeatherForecast&gt;&gt; GetFiveDayForecastAsync(string location, Unit unit = Unit.Metric)<br>{<br>    // [...]<br>    var response = await client.GetAsync(url);<br>    // [...]<br>    var json = await response.Content.ReadAsStringAsync();</pre><p>This ensures that the method waits until there’s a response from the HTTP client, then waits for the result to be encoded. If our method was also getting data from another source, or performing some other intensive operation, it could do that at the same time. As it is, our method isn’t performing differently, but using async features where possible is still usually best practice.</p><p>Run the application and test https://localhost:5001/WeatherForecast?location=chicago again to make sure no errors were introduced. If everything is still working as it did originally, then the refactoring is working.</p><h3>Summary</h3><p>The changes in this step haven’t been very drastic, but they at least establish some more sustainable patterns as we continue to build out this application. Now that our classes are more testable and using async methods when possible, the next step is to set up unit tests and use those tests to support adding better exception handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ddbfd50728a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/consuming-third-party-apis-in-asp-net-core-9ddbfd50728a">Consuming third-party APIs in ASP.NET Core</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up an N-Tier ASP.NET Core App]]></title>
            <link>https://jeremywellsio.medium.com/setting-up-an-n-tier-asp-net-core-app-d1fe859be338?source=rss-96da70f12595------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1fe859be338</guid>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Jeremy Wells]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 19:17:59 GMT</pubDate>
            <atom:updated>2020-06-22T19:17:59.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*kmsZXXnpRJVCy-zHRuhRWw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lenneek?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Elena Koycheva</strong></a> on <a href="https://unsplash.com/s/photos/three-layers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><h3>Introduction</h3><p>This is article #1 in a series of tutorials that walks through building and hosting an Angular and ASP.NET Core web application. The application will have extremely minimal functionality — a <a href="http://alistair.cockburn.us/index.php/Walking_skeleton">Walking Skeleton</a> — but it can serve as a template for building out functionality in more useful projects.</p><p>In the <a href="https://www.jeremywells.io/2020/06/11/starting-up-an-aspnetcore3-project.html">previous article</a>, I gave a more detailed overview of this series and walked through preparing a development environment for .NET Core. I also created and explained the default boilerplate code that comes from creating an ASP.NET Core WebApi application. For a little more background, I suggest reading through <a href="https://www.jeremywells.io/2020/06/11/starting-up-an-aspnetcore3-project.html">that article</a> first before stepping through this tutorial.</p><h3>Prerequisites</h3><p>For this tutorial, I’ll assume you’ll aren’t yet familiar with ASP.NET Core, but you have the .NET Core SDK and an IDE or text editor set up and ready to go, If not, <a href="https://www.jeremywells.io/2020/06/11/starting-up-an-aspnetcore3-project.html">the previous article</a> will go through that step. If this is your first time building a server-side application, or if you’re familiar with a comparable framework like Rails or Django, but haven’t tried one from the .NET Core family, then hopefully this article will clearly introduce you to the process with this framework. I won’t go into the syntax of the C# language (for that, I recommend <a href="https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/intro-to-csharp/">Microsoft’s introduction</a>), but I’ll explain the steps of building our application in detail.</p><h3>N-Tier architecture</h3><p>A common design pattern for web applications is called the <a href="https://martinfowler.com/bliki/PresentationDomainDataLayering.html">N-Tier Pattern</a>, where <strong>n</strong> is the number of layers of the application. <a href="https://en.wikipedia.org/wiki/Multitier_architecture">Wikipedia describes one N-Tier scenario</a> as a presentation tier, a logic tier, and a data tier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*8B9XpxK_SDtqPs_q.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Multitier_architecture"><strong>Wikipedia</strong></a></figcaption></figure><p>An important feature of this pattern is that a lower layer is not aware of any higher layers and changes to a higher layer do not affect lower layers. This pattern can present itself as simply a separation between client-side code, a service layer that contains the business logic, and a data-access layer for interfacing with a database. And this <a href="https://docs.microsoft.com/en-us/azure/architecture/guide/architecture-styles/n-tier#:~:text=An%20N%2Dtier%20architecture%20divides,layer%20has%20a%20specific%20responsibility.&amp;text=A%20traditional%20three%2Dtier%20application,tier%2C%20and%20a%20database%20tier.">Microsoft Azure article</a> describes a much more scaled version of this pattern that separates the tiers into a number of physical processes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BlexL6UFwNZqi9n_.png" /><figcaption>Source: <a href="https://docs.microsoft.com/en-us/azure/architecture/guide/architecture-styles/n-tier#:~:text=An%20N%2Dtier%20architecture%20divides,layer%20has%20a%20specific%20responsibility.&amp;text=A%20traditional%20three%2Dtier%20application,tier%2C%20and%20a%20database%20tier."><strong>Microsoft</strong></a></figcaption></figure><p>In our very simple application, the presentation layer will be an Angular client that we’ll build in a subsequent article. Our controller will represent a web tier and in this tutorial, we’ll build and secure a service as a business-logic tier that will call an external API.</p><p><strong>The result will be an API endpoint that returns the next 5 temperatures in a forecast by location.</strong></p><p>Here are the steps to get there:</p><ol><li>Sign up for and retrieve an API key to use the <a href="https://openweathermap.org/api">OpenWeatherMap</a> service.</li><li>Secure the API key so that it can be used in our application.</li><li>Build a service that handles requests to the OpenWeatherMap API.</li><li>Modify the controller to work with the service, then test it in <a href="https://www.postman.com/">Postman</a>.</li></ol><p>Going through these steps will demonstrate how ASP.NET Core uses <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1">dependency injection</a>, protects sensitive values such as API keys and database connection strings, and how it handles exceptions.</p><p>The starting point for this code can be found at <a href="https://github.com/jsheridanwells/WeatherWalkingSkeleton/tree/0_GettingStarted">this repo</a>. Using Git, you can clone the repo locally using:</p><pre>$ git clone -b 0_GettingStarted --single-branch git@github.com:jsheridanwells/WeatherWalkingSkeleton.git</pre><p>Then restore the project:</p><pre>$ dotnet restore</pre><h3>Getting the OpenWeatherMap API key</h3><p>Instead of returning random objects in the boilerplate code, we’ll return values from a live API. The <a href="https://openweathermap.org/api">OpenWeatherMap API</a> is an easy way to incorporate third-party data when testing out a project. You’ll need to create an account, then get an API key to be able to make requests from their service.</p><ol><li>Go to <a href="https://openweathermap.org/api">https://OpenWeatherMap.org/api</a> and click <strong>“Sign in”</strong>. Create an account if you haven’t before and log in.</li><li>If you are at <a href="https://home.openweathermap.org/">home.openweathermap.org</a>, at the top of the page is a nav item called <strong>“API keys”</strong>. Click that and you’ll arrive <a href="https://home.openweathermap.org/api_keys">here</a>.</li><li>Click the <strong>“Generate”</strong> button. Name the key and save it.</li><li>The table will now list your API key. We’ll copy this in the next step so that it’s available in our application.</li></ol><p>At this point, we can test out the OpenWeatherMap API to get an idea of the data structure it returns. <a href="https://www.postman.com/">Postman</a> is a great tool for this. You can download it <a href="https://www.postman.com/downloads/">from here</a> if you don’t have it yet.</p><p>We’ll test out the <a href="https://openweathermap.org/forecast5">5-day Weather Forecast</a> endpoint. There are a variety of ways to query this resource: We’ll query it by city name.</p><p>According to <a href="https://openweathermap.org/forecast5">the documentation</a>, the structure for the url is</p><pre>api.openweathermap.org/data/2.5/forecast?q={ city name }&amp;appid={ your api key }</pre><p>We’ll set that up in Postman by entering the url up to the resource name (forecast), then entering a city name and our api key in the query parameters table below. Also, you can add a units parameter with a value of either metric or imperial, otherwise the temperatures will be returned in Kelvin. Since I’m writing from the United States, I’ve opted for imperial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*XVO1-lZEVeUiB21i.png" /></figure><p>If everything is set up correctly, your response will be an array of 40 temperature objects for whatever city was selected. We’ll keep Postman open so that we can use the URL that was formed when we create a service in our web API to make this request.</p><h3>Securing our API key</h3><p>Although I’m having a hard time imagining what mischief could be made with my OpenWeatherMap API key, it’s still best practice to store the actual value separately from the source code. In a real project, there will be all kinds of secret keys, passwords, and database connections strings — and these values would be different from environment to environment — so here we’ll save the API key in our file system, then bring it into our application configuration. The <strong>User Secrets</strong> API that comes with the dotnet SDK is an ideal tool for this.</p><p>To accomplish this, we’ll:</p><ol><li>Create a class to help inject our key in the places where we need it.</li><li>Save our key to the file system using the dotnet cli.</li><li>Bring our key into the configuration schema in our project’s Startup.cs class.</li></ol><p>First, we’ll create a class called OpenWeatherMap and give it one property: ApiKey:</p><pre>$ mkdir Config<br>$ touch Config/OpenWeather.cs</pre><p>(Note: if you’re using Visual Studio, you can create this file using the <strong>Solution Explorer</strong>)</p><p>Add these contents to OpenWeather.cs:</p><pre>namespace WeatherWalkingSkeleton.Config<br>{<br>    public class OpenWeather<br>    {<br>        public string ApiKey { get; set; }<br>    }<br>}</pre><p>When the dotnet CLI saves secrets for a project, it’s in a directory structured as follows:</p><pre>$ ~/.microsoft/usersecrets/&lt;USER-SECRETS-ID&gt;/secrets.json</pre><p>The USER-SECRETS-ID is saved in the .csproj file at the root of the project. Any string will work as a user secrets ID, but for this project we’ll use a <a href="https://techterms.com/definition/guid#:~:text=A%20GUID%20is%20a%20128,keys%2C%20and%20various%20file%20types.">GUID</a>: 65988f0a-26ed-44ef-8749-f86a2f5c18a9 (you can also generate your own GUID if you prefer).</p><p>Open WeatherWalkingSkeleton.csproj and add the UserSecretID:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;netcoreapp3.1&lt;/TargetFramework&gt;<br>    &lt;UserSecretsId&gt;65988f0a-26ed-44ef-8749-f86a2f5c18a9&lt;/UserSecretsId&gt;<br>  &lt;/PropertyGroup&gt;<br>&lt;/Project&gt;</pre><p>Next, run the following command, replacing YOUR-API-KEY with the API key you generated when signing up for the OpenWeatherMap service:</p><pre>$ dotnet user-secrets set &quot;OpenWeather:ApiKey&quot; &quot;YOUR-API-KEY&quot;</pre><p>If you’re successful, you should see output like this:</p><pre>Successfully saved OpenWeather:ApiKey = YOUR-API-KEY to the secret store.</pre><p>Now that the key value is stored in our usersecrets/ directory, we need to bring it into the application. This is done in the Startup class by calling a method from the Configuration object, then adding it to the application’s service collection:</p><pre>// Startup.cs<br>using WeatherWalkingSkeleton.Config;<br><br>// [...]<br>    public class Startup<br>    {<br>        // [...]<br>        public void ConfigureServices(IServiceCollection services)<br>        {<br>            // Add OpenWeatherMap API key<br>            var openWeatherConfig = Configuration.GetSection(&quot;OpenWeather&quot;);<br>            services.Configure&lt;OpenWeather&gt;(openWeatherConfig);<br>            // [...]<br>        }</pre><p>Now the API key is available in the application when we use the OpenWeatherMap API. We’ll be able to confirm that later when we build a service to call the API.</p><h3>Classes for mapping the OpenWeatherMap API response</h3><p>Our next step is to create a service to sit between the WeatherForecastController and the OpenWeatherMap API. Ideally, a controller’s only responsibilities are to route requests to the right services and to return either success or error responses. All the business logic should be handled at the lower levels.</p><p>Before implementing the actual service though, we’ll need to create a class to <a href="https://stackoverflow.com/a/5660076">deserialize</a> the response we get from the OpenWeatherMap API. We’ll also create a class for our own API response that will organize the data the way we would like to present it.</p><p>First, delete the default ./WeatherForecast.cs class that was created when the project was bootstrapped.</p><p>We’ll create a Models/ directory, with two classes: a new and improved WeatherForecast which will be the object that gets returned from the WeatherForecastController, and an OpenWeatherResponse which we’ll use to deserialize the JSON data returned from OpenWeatherMap.</p><pre>$ mkdir Models<br>$ touch Models/{WeatherForecast.cs,OpenWeatherResponse.cs}</pre><p>After inspecting the response from OpenWeatherMap in Postman,…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*TUNPTColSfaXPs9-.png" /></figure><p>…we see an array called list. I’ve decided that I’d like our API to return the date and time, temperature, the “feels like” temperature, as well as the min and max temperatures for each item in that array. We’ll add those properties to the WeatherForecast model.</p><pre>// WeatherForecast.cs<br><br>using System;<br><br>namespace WeatherWalkingSkeleton.Models<br>{<br>    public class WeatherForecast<br>    {<br>        public DateTime Date { get; set; }<br>        public decimal Temp { get; set; }<br>        public decimal FeelsLike { get; set; }<br>        public decimal TempMin { get; set; }<br>        public decimal TempMax { get; set; }<br>    }<br>}</pre><p>Feel free to experiment and extract different kinds of values from this response as you follow along.</p><p>This class is pretty straightforward, but extracting these values from the OpenWeatherMap response, a rather complex JSON object, will take more work. The response is organized as follows:</p><ol><li>The root object contains an array property called list.</li><li>Each item in list contains a Unix timestamp called dt and an object called main.</li><li>main then holds the different temperatures that we want.</li></ol><p>To deserialize this response into a C# object, we’ll create three classes, and leverage a library called System.Text.Json which is <a href="https://www.hanselman.com/blog/SystemTextJsonAndNewBuiltinJSONSupportInNETCore.aspx">included in ASP.NET Core as of version 3x</a>.</p><p>Add the following to OpenWeatherResponse.cs:</p><pre>// OpenWeatherResponse.cs<br><br>using System.Collections.Generic;<br>using System.Text.Json.Serialization;<br><br>namespace WeatherWalkingSkeleton.Models<br>{<br>    public class OpenWeatherResponse <br>    {<br>        [JsonPropertyName(&quot;list&quot;)]<br>        public List&lt;Forecast&gt; Forecasts { get; set; }<br>        <br>    }<br>    // [... continue to add here]<br>}</pre><p>We’ll name the root object OpenWeatherResponse. The System.Text.Json library provides a data annotation called JsonPropertyName which allows us to indicate the json property that we’re extracting these values from. This way we can take an array originally called list and name it something more meaningful in this context: Forecasts.</p><p>We’ll create a Forecast class that will hold the dt and main properties from the API response:</p><pre>// OpenWeatherResponse.cs<br>// [...]<br>    public class Forecast<br>    {<br>        [JsonPropertyName(&quot;dt&quot;)]<br>        public int Dt { get; set; }<br>        [JsonPropertyName(&quot;main&quot;)]<br>        public Temps Temps { get; set; }    <br>    }<br>// [...]</pre><p>By taking the values from main and renaming them Temps, our own code will be easier to understand.</p><p>Below the Forecast class, we’ll add the final class called Temps to indicate which temperature values to include. As before, we can use JsonPropertyName to name our properties with the conventional C#-style casing.</p><pre>// OpenWeatherResponse.cs<br>// [...]<br>    public class Temps<br>    {<br>        [JsonPropertyName(&quot;temp&quot;)]<br>        public decimal Temp  { get; set; }<br>        [JsonPropertyName(&quot;feels_like&quot;)]<br>        public decimal FeelsLike { get; set; }<br>        [JsonPropertyName(&quot;temp_min&quot;)]<br>        public decimal TempMin { get; set; }<br>        [JsonPropertyName(&quot;temp_max&quot;)]<br>        public decimal TempMax { get; set; }<br>    }<br>// [...]</pre><p>Now that a strategy for handling the API data is in place, the next step is to call the API with a service.</p><h3>Setting up and injecting an ASP.NET Core service</h3><p>As mentioned earlier, ASP.NET Core uses dependency injection as a primary design consideration, and we’ll see how this works here as we implement a service that calls the OpenWeatherMap API and returns the data as a WeatherForecast object. Our service will be called OpenWeatherService with a method called GetFiveDayForecast. The method will take a location and a unit of measurement to use when calling the API. The service will be represented in other classes as an interface called IOpenWeatherService.</p><p>We’ll build it in such a way that we can verify that the service is wired up correctly in the application first before getting into actual functionality: We’ll create the service class, create the interface, register the types in Startup, then inject them into the WeatherForecastController. After these steps, we’ll implement the actual GetFiveDayForecast method.</p><p>Create a new file to hold the service and the interface:</p><pre>$ mkdir Services<br>$ touch Services/OpenWeatherService.cs</pre><p>Normally, we would have the interface and the class in separate files, but since this class will only have one method right now, we’ll keep them together. Add the following to create the IOpenWeatherService interface:</p><pre>using System;<br>using System.Collections.Generic;<br>using WeatherWalkingSkeleton.Models;<br><br>namespace WeatherWalkingSkeleton.Services<br>{<br>    public enum Unit<br>    {<br>        Metric,<br>        Imperial,<br>        Kelvin<br>    }<br><br>    public interface IOpenWeatherService<br>    {<br>        List&lt;WeatherForecast&gt; GetFiveDayForecast(string location, Unit unit = Unit.Metric);<br>    }<br>    // [...]<br>}</pre><p>Our interface defines a method that accepts a location and a unit of measurement, and we’ve restricted it to the three acceptable options using an <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum">enum</a>. The method will return a list of objects of the WeatherForecast type that we defined earlier.</p><p>Below the interface we’ll add a service class to implement the method:</p><pre>public class OpenWeatherService : IOpenWeatherService<br><br>    public List&lt;WeatherForecast&gt; GetFiveDayForecast(string location, Unit unit = Unit.Metric)<br>    {<br>       return new NotImplementedException(); <br>    }</pre><p>So far, the only thing the method does is raise an exception to say it’s not ready yet. We’ll leave it this way for now so that we can register it in the Startup class and inject it into the controller. Then we can do a quick test with the controller to make sure the method is getting called. After that, we’ll build out the method.</p><p>Open Startup.cs again and find the ConfigureServices method. Below the line where we brought in the API key, add the following line:</p><pre>public class Startup<br>    {<br>        // [...]<br>        public void ConfigureServices(IServiceCollection services)<br>        {<br>            // [...]<br>            services.AddScoped&lt;IOpenWeatherService, OpenWeatherService&gt;();<br>            // [...]<br>        }<br>    }</pre><p>services.AddScoped is the method telling the application to instantiate an OpenWeatherService object whenever another class depends on the IOpenWeatherService interface. ASP.NET Core provides three methods for registering dependencies: AddSingleton which initializes an object once during the application lifecycle, AddScoped which keeps the same object available during a single request before disposing it, and AddTransient which provides a new instance every time it is injected. The <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#service-lifetimes-and-registration-options">Microsoft docs</a> explain service lifetimes in more detail.</p><p>Next, we’ll modify the WeatherForecastController to return data from the OpenWeatherService instead of random values.</p><p>First, we will inject IOpenWeatherService in the class constructor and make it available as a private property called _weatherService.</p><pre>using WeatherWalkingSkeleton.Services;<br><br>namespace WeatherWalkingSkeleton.Controllers<br>{<br>    public class WeatherForecastController : ControllerBase<br>    {<br><br>        private readonly IOpenWeatherService _weatherService;<br><br>        public WeatherForecastController(ILogger&lt;WeatherForecastController&gt; logger, IOpenWeatherService weatherService)<br>        {<br>            _logger = logger;<br>            _weatherService = weatherService;<br>        }<br>        // [...]<br>    }<br>}</pre><p>Next, we’ll change the Get method to use the data returned from the service.</p><pre>[HttpGet]<br>        public IActionResult Get()<br>        {<br>            var forecast = _weatherService.GetFiveDayForecast(&quot;Chicago&quot;);<br>            return Ok(forecast);<br>        }<br>    }</pre><p>Anything else in the controller can be deleted.</p><p>Instead of producing values directly in the controller, we’re returning the result of data produced elsewhere, so our return type will be IActionResult. We’re receiving an object we’ll call forecast from the OpenWeatherService, and we’ll pass it on in the body of a “Success” response: Ok(). Also, for now, I’ve hard-coded “Chicago” as the argument for GetFiveDayForecast to that everything will compile. Later, we’ll modify Get again to accept query parameters.</p><p>Let’s do a quick test to make sure that OpenWeatherService.GetFiveDayForecast() is being called within the application. Run the application ($ dotnet run) and call the WeatherForecastController from Postman or a browser (https://localhost:5001/WeatherForecast). The response we expect looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*zHieu4J3XMGmGHUf.png" /></figure><p>Since the stack trace is throwing a NotImplementedException called from the OpenWeatherService in our WeatherForecastController, everything is working as expected. Now, we’ll make our five-day forecast method actually work.</p><h3>Implementing our HTTP service</h3><p>Open OpenWeatherService.cs back up. The plan for our GetFiveDayForecast method is for it to do what we were doing before in Postman: make a GET request to the OpenWeatherMap API and map the values we want as a list of WeatherForecast objects.</p><p>The first thing to do is to build a URL so that it looks like the URL that was successful for us when testing the API in Postman, e.g.:</p><pre>api.openweathermap.org/data/2.5/forecast?q=Chicago&amp;appid=YOUR-API-KEY8&amp;units=imperial</pre><p>First, we need to extract the API key from the configuration of our application. At the top of the class we’ll create a constructor that injects an instance of IOptions:</p><pre>using Microsoft.Extensions.Options;<br>using WeatherWalkingSkeleton.Config;<br>    // [...]<br>    public class OpenWeatherService : IOpenWeatherService<br>    {<br>        private OpenWeather _openWeatherConfig;<br><br>        public OpenWeatherService(IOptions&lt;OpenWeather&gt; opts)<br>        {<br>            _openWeatherConfig = opts.Value;<br>        }<br>        // [...]<br>    }</pre><p>Using the OpenWeather type, we can deserialize the value of our API key from the local environment without having to write it anywhere in the code. We’ll store it as a private property called _openWeatherConfig. With the API key, along with the location and unit of measurement coming in as method arguments, we have the values needed to build the URL. We’ll do that on the first line of the GetFiveDayForecast method:</p><pre>public List&lt;WeatherForecast&gt; GetFiveDayForecast(string location, Unit unit = Unit.Metric)<br>        {<br>            string url = $&quot;https://api.openweathermap.org/data/2.5/forecast?q={ location }&amp;appid={ _openWeatherConfig.ApiKey }&amp;units={ unit }&quot;;<br>            // [...]<br>        }</pre><p>If you are handy with the debugger in the IDE that you’re using, you should set a breakpoint here and inspect the value of _openWeatherConfig.ApiKey.</p><p>Next we’ll create a list of forecasts that the method will return:</p><pre>using WeatherWalkingSkeleton.Models;<br>// [...]<br>        public List&lt;WeatherForecast&gt; GetFiveDayForecast(string location, Unit unit = Unit.Metric)<br>        {<br>            string url = $&quot;https://api.openweathermap.org/data/2.5/forecast?q={ location }&amp;appid={ _openWeatherConfig.ApiKey }&amp;units={ unit }&quot;;<br>            var forecasts = new List&lt;WeatherForecast&gt;();<br>            <br>            return forecasts;<br>        }</pre><p>In the middle is where we add the logic to:</p><ol><li>Make a GET request to the OpenWeatherMap API,</li><li>Deserialize the response,</li><li>And use the response to build the list of WeatherForecast object we’re returning.</li></ol><p>That implementation can be described as follows:</p><pre>// 0. Use the .NET HttpClient library<br>            using (HttpClient client = new HttpClient())<br>            {<br>                // 1. Make the request<br>                var response = client.GetAsync(url).Result;<br>                var json = response.Content.ReadAsStringAsync().Result;<br><br>                // 2. Deserialize the response.<br>                var openWeatherResponse = JsonSerializer.Deserialize&lt;OpenWeatherResponse&gt;(json);<br><br>                // 3. Build the list of forecasts<br>                foreach (var forecast in openWeatherResponse.Forecasts)<br>                {<br>                    forecasts.Add(new WeatherForecast<br>                    {<br>                        Date = new DateTime(forecast.Dt),<br>                        Temp = forecast.Temps.Temp,<br>                        FeelsLike = forecast.Temps.FeelsLike,<br>                        TempMin = forecast.Temps.TempMin,<br>                        TempMax = forecast.Temps.TempMax,<br>                    });<br>                }<br>            }</pre><p>The entire method should now look like this:</p><pre>public List&lt;WeatherForecast&gt; GetFiveDayForecast(string location, Unit unit = Unit.Metric)<br>        {<br>            string url = $&quot;https://api.openweathermap.org/data/2.5/forecast?q={ location }&amp;appid={ _openWeatherConfig.ApiKey }&amp;units={ unit }&quot;;<br>            var forecasts = new List&lt;WeatherForecast&gt;();<br>            using (HttpClient client = new HttpClient())<br>            {<br>                var response = client.GetAsync(url).Result;<br>                var json = response.Content.ReadAsStringAsync().Result;<br>                var openWeatherResponse = JsonSerializer.Deserialize&lt;OpenWeatherResponse&gt;(json);<br>                foreach (var forecast in openWeatherResponse.Forecasts)<br>                {<br>                    forecasts.Add(new WeatherForecast<br>                    {<br>                        Date = new DateTime(forecast.Dt),<br>                        Temp = forecast.Temps.Temp,<br>                        FeelsLike = forecast.Temps.FeelsLike,<br>                        TempMin = forecast.Temps.TempMin,<br>                        TempMax = forecast.Temps.TempMax,<br>                    });<br>                }<br>            }<br>            <br>            return forecasts;<br>        }</pre><p>Start the application again, make the same API request to /WeatherForecast and we should now see actual data.</p><p>The final bit of functionality we’ll need is to update the controller so that we can also send location and unit of measurement parameters with our requests. Back in WeatherForecast.cs, we’ll add two arguments to the Get method and use those when we call GetFiveDayForecast:</p><pre>public IActionResult Get(string location, Unit unit = Unit.Imperial)<br>{<br>    var forecast = _weatherService.GetFiveDayForecast(location, unit);<br>    return Ok(forecast);<br>}</pre><p>The ASP.NET Core ControllerBase class has several ways to extract parameters and data from HTTP requests. Here, if we simply add arguments to a controller method, and add the matching names in the URL…</p><pre><a href="https://localhost:5001/WeatherForecast?location=london&amp;unit=kelvin">https://localhost:5001/WeatherForecast?location=london&amp;unit=kelvin</a></pre><p>…the controller will bring them in as parameters.</p><p>Run the application again, make a POSTMAN request at the above url. If everything is great, you should see a response like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*i9WoZvGIRoEDQznm.png" /></figure><h3>Summary</h3><p>Now that we’ve got an API of our own returning real data, now is a good stopping point before building in a little more infrastructure in this project. We’ll do that in future tutorials.</p><p>Using the above steps, we were able to conceal a secret API key using .NET Core’s user secrets. We built out a service class to pull data from an external resource and modified a controller class so that it is limited to simply relaying requests and responses. We also saw how the Startup class in an ASP.NET Core application sets up dependency injection and configures services using values from the host environment. With this basic functionality in place, we’ll be able to explore some of the other necessary components to deploy a working walking skeleton and have a solid reference for putting together our real projects.</p><p>To reference the code that was created in this tutorial, see the 1_aspnetcore_webapi_setup branch in its <a href="https://github.com/jsheridanwells/WeatherWalkingSkeleton/tree/1_aspnetcore_webapi_setup">Github repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1fe859be338" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>