Setting up Jenkins in Azure

Before getting started, you’ll need to have:

  • An Azure tenant and subscription.
  • OpenSSH (installation for Windows 10)

Installing Jenkins via Azure Marketplace

The easiest way to install Jenkins is to use the Azure Marketplace link. A couple suggestions when setting up:

  • I recommend using an SSH Public Key to sign in. If you haven’t yet, generate one using ssh-keygen and then get it using cat ~.ssh\id_rsa.pub
  • Set up a domain name label, especially if you aren’t planning to put this behind a different domain.
  • Set the VM as B1ms starting off – you can upgrade later as the system is used more.

After creation, modify the NSG created and use your public IP to secure SSH access (check your public IP).

Next, SSH into the server using the IP and check to see if you can update the OS (as of this writing, the image ships with Ubuntu 16.04 LTS, and can be upgraded to 18.04 LTS).

Connecting a Domain

If you’re planning to use a different domain to host Jenkins (as opposed to the provided domain-name-label.location.cloudapp.azure.com), set the following DNS record:

  • CNAME
  • Host: desired subdomain (ex. jenkins -> jenkins.dfar.io)
  • Value: DNS record from Azure.

Since DNS will take a second, check to verify you can access the new server.

Setting up SSL using Let’s Encrypt

The next step is setting up SSL using Let’s Encrypt to allow for an HTTPS connection. First, open the 443 port on the VM:

az network nsg rule update -g RG_NAME --nsg-name NSG_NAME -n http-rule --destination-port-ranges 80, 443

Now SSH into the server and modify SSL Offloading:

sudo nano /etc/nginx/sites-available/default

Use the following configuration:

server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name CUSTOMDOMAIN;
    ssl_certificate /etc/letsencrypt/live/CUSTOMDOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/CUSTOMDOMAIN/privkey.pem;
    location / {
        proxy_set_header        Host $host:$server_port;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;


        # Fix the “It appears that your reverse proxy set up is broken" error.
        proxy_pass          http://localhost:8080;
        proxy_read_timeout  90;
    }
}

Then run the following commands:

sudo service nginx stop
git clone https://github.com/letsencrypt/letsencrypt
./letsencrypt/letsencrypt-auto certonly
sudo service nginx restart

Accessing and Logging Into Jenkins

After completed, access the Jenkins instance at your domain. Verify that both the SSL connection is valid and that you are on the ‘Unlock Jenkins’ page:

Run the following command in the SSHed server to get a code for the screen:

sudo cat /var/lib/jenkins/secrets/initialAdminPassword

Next, you’ll get a request to either install suggested plugins or select plugins as desired. I recommend going through and selecting the plugins desired to keep the installation minimal. Remove anything from the list that you may not need (such as Subversion). You can always add plugins later if you find you need.

After that, create an admin user for yourself, and you’ll be ready to get started!

Next Steps

After you’ve finished setting up Jenkins, a few next steps would be:

Reference

Creating a nopCommerce Plugin in version 3.90 and below

I recently worked with a client using an older version of nopCommerce that needed to have a plugin made for functionality. In particular, this plugin integrates with updown.io to allow for turning checks on and off during scheduled maintenance.

To do this, you’ll need to have the nopCommerce source code available for use.

Creating the Plugin

To get started, create a Class Library in the Plugins folder:

  • Make sure to change the location to the plugin folder below the name.
  • Use naming convention Nop.Plugin.{category}.{name}
  • The categories you can use include:
    • ExternalAuth
    • Widgets
    • ExchangeRate
    • DiscountRules
    • Payments
    • Shipping
    • Tax
    • Misc

Next, go into properties and make sure your Target framework is .NET Framework 4,.5.1.

Next, change the output path for all configurations to deploy to:

..\..\Presentation\Nop.Web\Plugins\{group}.{name}\

This will build the output of the plugin into the Web project, which will ultimately deploy to the nopCommerce application.

After that, copy a web.config file from another plugin.

Next, create a Description.txt file with the following content:

Group: {group}
FriendlyName: {friendly name}
SystemName: {group}.{name}
Version: 0.1
SupportedVersions: {your version of nopCommerce}
Author: {you}
DisplayOrder: 1
FileName: Nop.Plugin.{group}.{name}.dll
Description: {a description}

Set both the web.config and Description.txt files to ‘Copy if newer’.

Finally, there is a Class.cs file that was created when creating the Class Library. Rename the file to {name}Plugin.cs and use the following code snippet:

public class YourPlugin : BasePlugin, IMiscPlugin
    {
        public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
        {
            actionName = "Configure";
            controllerName = "Your";
            routeValues = new RouteValueDictionary()
            {
                { "Namespaces", "Nop.Plugin.Misc.Your.Controllers" },
                { "area", "" }
            };
        }
    }

Once this is done, you should be able to clean, build, and publish the project. Check the plugins list of the admin backend to see your plugin listed:

Just to ensure everything is working, go ahead and install the plugin. The plugin should install successfully, and the plugin will then be running on your site. You’re now ready to make changes to the plugin to modify NopCommerce capabilities.

Next Steps

After the initial plugin was created, next steps include:

  • Creating a logo named logo.png and upload it to the plugin. Set the image to ‘Copy if newer’ and size the image to around 50×50.
  • Set up a configuration page to allow for customizing data on the plugin (notice that for now, clicking on ‘Configure’ if applicable will crash the site.)

Reference: 
http://docs.nopcommerce.com/pages/viewpage.action?pageId=22675509

SSHing into an Azure Kubernetes Service node

First, a few reasons why you might do this:

  • If you were looking to view and/or retrieve files from the node itself, perhaps generated by a pod.
  • If you wanted to get more information on the OS running for the node.

Generate an SSH Key

First, generate an SSH key to connect to the server with, noting where you save:

ssh-keygen

Add Public SSH Key to Node

Next, add your generated public SSH key to the node, alongside a user:

az vm user update --resource-group <RESOURCE_GROUP> --name <NODE_NAME> --username azureuser --ssh-key-value <PUBLIC_SSH_KEY_LOCATION>

Setting up to SSH

To actually SSH into the node, there are two ways you can do this:

  1. Open the node via a public IP address and SSH into it directly from your machine. This is the easiest and my preferred way to do this, but requires the ability to make changes to the network interface of the node.
  2. Create a pod with OpenSSH installed to ssh into the node while connected.

Method 1: Public IP Address

First, access the network interface of the node you’re trying to access. Access IP Configurations, and click the ‘ipconfig1’ configuration. Add a public IP:

Next, create an NSG rule for the cluster with the following info:

  • Source: your local IP address (https://canihazip.com/s)
  • Destination: the private IP address of the node.
  • Destination port ranges: 22
  • Protocol: TCP

Method 2: Creating OpenSSH Pod

I’ll fill this out at some point.

SSHing into the Node

After following either of the methods above, the final step is actually SSHing into the node. If you’ve been using PowerShell here, I’d switch to WSL:

sudo ssh -i <PUBLIC_SSH_KEY_DIR> azureuser@<PUBLIC_IP>

Clean Up

Once you’ve finished, I recommend:

  • Removing the SSH access rule from the NSG.
  • Removing the public IP address from the AKS node network interface.
]]>

Keeping Track of Apparel in NopCommerce by Size

Setting the Product to Use Attributes For Inventory
  • View the product using the “Advanced” view
  • Set the Inventory Method for the product to be “Track inventory by product attributes”
  • Optionally, set “Display availability” and “Display stock quantity”

Adding Inventory for the Product

  • Go to “Product Attributes” -> “Attribute Combinations”
  • You should see a listing of the different sizes available – if not, click the “Generate all possible combinations” button.
  • Change the stock count for each item as needed:
]]>

Setting up WordPress to force SSL in the Admin Area

Recently, I ran into an issue when trying to migrate an existing WordPress website to start using HTTPS, especially in the admin area. Even after migrating everything in the database over to use HTTPS, I ran into a 302 redirect issue when trying to log in.

NOTE: make sure an SSL certificate is configured for the site, or you’ll receive an invalid certificate error.

Add the following to your wp-config.php file at the very top (if you don’t add to top, you’ll run into yet another issue where your users will not have permissions to access anything in admin):

<?php

define('FORCE_SSL_ADMIN', true);

// in some setups HTTP_X_FORWARDED_PROTO might contain
// a comma-separated list e.g. http,https
// so check for https existence
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
$_SERVER['HTTPS']='on';


...

With this in place, you’ll see when you go into the administration area, you’ll always be redirected to use HTTPS.

Reference: https://codex.wordpress.org/Administration_Over_SSL

]]>

Create a Java Web App with Spring Boot Starter, Gradle, and Azure Active Directory

Working on a project that would eventually use Azure Active Directory for authentication, I wanted to use Microsoft’s guide to get started with an app that could authenticate. However, the guide is written using Maven – and in our case, we are using Gradle for builds across the ecosystem.

I was able to mostly follow the guide provided, but ran into a gotcha – involving having to add a fixed dependency to get the system working. In addition, I added a secondary API endpoint to allow for testing both with and without group authentication.

To get started, you’ll need the following:

Create an App With Spring Initializr

To get started, create an app at https://start.spring.io/ with the following information:

  • Project: Gradle
  • Project Metadata Artifact: oauth2-demo-gradle
  • Dependencies: Web, Security, Azure Active Directory

After clicking ‘Generate Project’, a ZIP file will be created. Extract this file to someone on your local machine, as you’ll be configuring it later.

Set Up Azure Active Directory

After the app is created, the next step is setting up Azure Active Directory for authentication. Follow the Create Azure Active Directory instance section, taking note of the App Registration information provided.

Once you get to the section involving configuration of the app, come back to this guide – you’ll make specific changes to make the testing experience both compatible with Gradle and a little more user-friendly.

Configure and Compile the App

Once Azure Active Directory is configured, open your Java IDE and import the build.gradle file as a project. After that’s done, there are a few files to configure/create.

Add the following dependencies into the build.gradle file (notice the third dependency, if this one is not added, you’ll run into an exception when testing):

implementation 'org.springframework.security:spring-security-oauth2-client'
implementation 'org.springframework.security:spring-security-oauth2-jose'
implementation 'com.nimbusds:oauth2-oidc-sdk:5.64.4'

Edit /src/main/resources/application.properties to look like the following:

# Specifies your Active Directory ID:
azure.activedirectory.tenant-id=22222222-2222-2222-2222-222222222222

# Specifies your App Registration's Application ID:
spring.security.oauth2.client.registration.azure.client-id=11111111-1111-1111-1111-1111111111111111

# Specifies your App Registration's secret key:
spring.security.oauth2.client.registration.azure.client-secret=AbCdEfGhIjKlMnOpQrStUvWxYz==

# Specifies the list of Active Directory groups to use for authorization:
azure.activedirectory.active-directory-groups=Users

Create a file called /controller/HelloController.java and add the following:

package com.example.oauth2demogradle.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;

@RestController
public class HelloController {
    @Autowired
    @RequestMapping("/version")
    public String helloWorld() {
        return "Hello World! (no auth required)";
    }

    @Autowired
    @RequestMapping("/secure")
    public String helloWorldSecure() {
        return "Hello World! (authenticated in Azure AD)";
    }

    @Autowired
    @PreAuthorize("hasRole('bams-devops')")
    @RequestMapping("/secureByGroup")
    public String helloWorldByGroup() {
        return "Hello World! (pre-authorized via AD group)";
    }
}

Create another file called security/WebSecurityConfig.java and add the following:

package com.example.oauth2demogradle.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/version").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .userInfoEndpoint()
                .oidcUserService(oidcUserService);
    }
}

Build and Verify App

Now that the configuration is complete, next step is building and testing. Run the following Gradle commands (easy way to do this is through the IDE):

clean
build
bootRun

You should end up with a log like the following:

Once this is confirmed, access http://localhost:8080/version. You should be able to access without logging into Azure.

Next, check http://localhost:8080/secure. You should receive a request to log in to Azure services. Log in as the user created in the step above, and you should be able to get a Hello World message.

Finally, confirm that the /secureByGroup endpoint is also working. This endpoint will verify the logged in user is part of a verified group.

This code can be found at

Reference: https://docs.microsoft.com/en-us/java/azure/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory?view=azure-java-stable

]]>

Delete Recovery Containers in Azure

While doing some clean-up of a collection of Azure resources, I came across difficulty when trying to delete Azure Site Recovery resources. Specifically, when trying to delete the Recovery Services vault, I’d receive this ‘Vault deletion error’:

Vault deletion error message

Furthermore, when trying to use the portal to delete the existing containers, I would end up with a delay in the actual deletion of the containers. I ended up looking through Azure CLI does and finding a way to programmatically delete the containers.

First, find the subscription ID of your Azure tenant, and use the following command:

Connect-AzureRmAccount -Subscription "<SUBSCRIPTION_ID>"

Next, connect to the Azure Recovery Vault using the Resource Group name and Vault name:

$rv = Get-AzureRmRecoveryServicesVault -ResourceGroupName "<RESOURCE_GROUP_NAME>" -Name "<VAULT_NAME>"
Set-AzureRmRecoveryServicesVaultContext -Vault $rv

Finally, you can run the following command to delete a recovery container from the vault. Use this for each of the containers:

$Cont = Get-AzureRmRecoveryServicesBackupContainer -ContainerType "AzureVM" -FriendlyName "<CONTAINER_NAME>" -ResourceGroupName "<RESOURCE_GROUP_NAME>"

$BackupItem = Get-AzureRmRecoveryServicesBackupItem -Container $Cont -WorkloadType "AzureVM"

Disable-AzureRmRecoveryServicesBackupProtection -Item $BackupItem -RemoveRecoveryPoints -Force

After deleting all the containers, you should be able to delete the Recovery vault without any issues.

]]>

Setting up OpenVPN on Azure From Scratch

Why do this? One of the major benefits being able to use the internet with a specified IP address. If you’re going to be working systems that whitelist specific IP addresses, you can use this solution to allow for access regardless of both machine and location.

This guide assumes that you:

  • Have an Azure subscription in place.
  • Have a means of SSHing into a virtual machine, such as OpenSSH.

Creating the Virtual Machine

First, access the Azure Marketplace image for OpenVPN.

Next, fill out the form to create a virtual machine with OpenVPN pre-installed. The following information

Once you’re finished, it should look like this:

After creating the virtual machine, access it via the Azure portal and take note of the Public IP address – you’ll use this to SSH into the server and complete the installation:

Creating and Securing the Domain Using Let’s Encrypt

You may want to run OpenVPN using a domain. You have two options:

  1. Use the domain provided by Azure.
  2. Add a CNAME record to a domain you already own.

Access the Public IP and create a DNS name label.

Verify you can access the OpenVPN server using the domain provided by Azure (making sure to use HTTPS).

If desired, you can also create a subdomain (such as vpn.<your-domain>.com). Create a CNAME record that looks like the following:

  • Host: vpn
  • Value: use the Azure domain provided above.

Let DNS propagate (might take a second), and try accessing with your own domain.

Now, whether you use Azure’s domain or your own, the next step is to set up a certificate with Let’s Encrypt:

SSH into the server using OpenSSH and the admin credentials created when creating the virtual machine:

ssh <ADMIN_NAME>@<YOUR_DOMAIN_NAME>

Use the CertBot site to generate instructions for installation, using the following commands for guidance (you are using ‘None of the above’ for the software)

lsb_release -a #determine the OS

Before starting, you will need to run the following to allow for DNS:

echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf > /dev/null

Run the commands provided by CertBot to obtain your cert (spin up a temporary webserver). When doing this, you will need to open Port 80 to allow Let’s Encrypt to connect.

Verify that accessing the site using HTTPS will result in a secure connection.

Running The OpenVPN Installation

Once SSHed into the virtual machine, you’ll be asked to complete the OpenVPN installation. For most settings, you’ll just use default options. After the installation is complete, you’ll need to reset the admin password:

sudo su -
passwd openvpn

Once this is done, verify the installation is complete and access the OpenVPN admin section at the following URL: https://<YOUR_PUBLIC_IP>/admin. Log in using the following credentials:

  • Username: openvpn
  • Password: the password generated in the step above.

Once this is done, you’ll want to change the server name to the generated public IP address from Azure. Go to ‘Network Settings’ and change the IP address to reflect your public IP, alongside making the following changes:

Setting up OpenVPN Connect

To verify that VPN is working and that you can connect, access the URL https://<PUBLIC_IP>. Log in using the same credentials above and download the OpenVPN Connect application for your operating system.

Once this is done, you can import the record from the server, and log in using the credentials provided above.

Finally, you can verify everything is working by checking your IP again. If your IP address matches the VPN server, you’ve successfully set up the VPN!

Next Steps

  • Remove SSH access to the server, requiring whitelisting again from Azure to allow for configuration.

]]>

How I Set Up My iPhone

Recently, I had to purchase an iPhone XS after having my iPhone 7 break, causing a need to set up my phone again after years of being used to my configuration. I decided I want to write this down in case I need to do this again in the future.

Initial Setup

The first thing to do when setting up the iPhone is going through settings and changing a variety of the settings I prefer. This includes:

  • Connecting to my home WiFi.
  • Connecting to my Bluetooth devices (my headphones and my car).
  • Scheduling Do Not Disturb from 10pm to 7am.
  • Setting up Downtime from 10pm to 7am.
  • Turning on Automatic Updates.
  • Turn on Screen Recording shortcut in the Control Panel.
  • Scheduling Night Shift from 10pm to 7am.
  • Setting Wallpaper (both lock and home screens).
  • Set MMS message history to 30 days.
  • Record video at 4K, 60 FPS.

Once that’s complete, most of the basic configuration for the phone is set. The next step is adding and configuring apps – let’s move on.

App Installlation and Configuration

My preference is to keep things as simple as possible, so I only keep three rows of apps available at any point on the home screen. I start by deleting all of the apps possible on the phone I’m not planning to use. Generally, that’s everything except the Notes app.

After that, I install my primary applications:

  • Google Maps (log in)
  • Hulu (log in)
  • Kindle (log in)
  • Slack (connect to workspaces)
  • WordPress (connect to all revelant websites)
  • Yelp
  • YNAB (log in)
  • YouTube (should auto log in from Google Maps)
  • Outlook (add email addresses)
  • Messenger (log in)
  • RTM (use badge count for tasks due today)

And then a few of the apps I leave in the ‘Utilities’ folder:

  • Dark Sky (turn on precipitation warnings, server weather alerts)
  • Discord (log in)
  • Dropbox (log in, set up camera uploads)
  • Facebook (log in)
  • Fitbit (log in, connect Fitbit)
  • Fly Delta (log in)
  • Genisys (log in)
  • Instagram (log in)
  • Life Cycle (activate)
  • Pluralsight (log in)
  • Google Sheets (log in)
  • WhatsApp (log in)

Most of these apps require configuring – so I go through each one and make sure everything is in place (logged in, etc.).

Final Steps

Once I have most everything set up, there’s a few more things I do to finish the process:

  • Set up widgets to display calendar and weather
  • Set a 15 minute time limit for Facebook and Instagram.
]]>

API Vs. Microservices: A Microservice Is More Than Just an API

When writing software, consider both the implementation and the architecture of the code. The software you write is most effective when written in a way that logically makes sense. In addition to being architecturally sound, software should also consider the interaction the user will have with it and the interface the user will experience.

Both the concept of an API and the concept of a microservice involve the structure and interactions of software. A microservice can be misconstrued as simply an endpoint to provide an API. But microservices have much more flexibility and capabilities than that. This article will speak on the differences between APIs and microservices, plus detail some of the benefits a microservice can provide.

To get started, let’s define our terms.

What Is an API?

First, let’s define what an API is. According to Wikipedia, an API (application programming interface) is:

a set of subroutine definitions, communication protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication between various components.

An easy way to think about an API is to think of it as a contract of actions you can request for a particular service. APIs are in use today in a multitude of web applications, such as social media, banking software, and much more. The standardized contract allows for external applications to interface with another.

For instance, let’s say you’re building an application that’s going to integrate with Facebook. You would be able to use the Facebook Graph API to access data inside Facebook, such as users, post, comments, and more. The API simplifies the complexity of trying to use the data inside Facebook and provides an easy-to-use way for the developer to access that data.

Common API Actions

In today’s world, APIs are usually developed using a RESTful style. These APIs will have a series of verbs associating with HTTP actions, like the following:

  • GET (get a single item or a collection)
  • POST (add an item to a collection)
  • PUT (edit an item that already exists in a collection)
  • DELETE (delete an item in a collection)

The advantage of this consistency through different applications is having a standard when performing various actions. The four different HTTP verbs above correlate with the common CRUD capabilities that many applications use today. When working with different APIs in one application, this makes for a recognizable way to understand the implications of the actions taken across different interfaces.

If you’re interested in working with an interactive example, take a look at Reqres. Reqres provides mock data for interfacing with a RESTful API and the actions you can take when interacting with an API.

Okay, now that we have that covered, let’s take a look at microservices.

What Is a Microservice?

Wikipedia defines a microservice as:

software development technique—a variant of the service-oriented architecture (SOA) architectural style that structures an application as a collection of loosely coupled services. In a microservices architecture, services are fine-grained and the protocols are lightweight.

But before we dig deeper into what microservices are and how they can be useful, let’s take a quick look into the monolith. Understanding how microservices differ from monoliths will give you a better sense of the benefits of moving to a microservices architecture.

The Precursor to Microservices: Monoliths

In the early days of software development (and continuing in many large enterprise environments today), there’s the concept of a monolith. A monolith is a single application that holds a full collection of functionality, serving as one place to store everything. Architecturally, it looks like this:

All of the components of the application reside in one area, including the UI layer, the business logic layer, and the data access layer. Building applications in a monolith is an easy and natural process, and most projects start this way. But adding functionality to the codebase causes an increase in both the size and complexity of the monolith, and allowing a monolith to grow large comes with disadvantages over time. Some of these include:

  • Risk of falling into the big ball of mud anti-pattern, not having any rhyme or reason in their architecture and difficult to understand from a high level.
  • Restriction of the technology stack inside the monolith. Especially as the application grows, the ability to move to a different technology stack becomes more and more difficult, even when the technology proves to no longer be the best choice.
  • Making changes to the codebase affects the entire application, no matter how small. For example, if just one of the business logic sections is receiving constant changes, this forces redeployment of the entire application, wasting time and increasing risk.

So what’s the alternative to building a monolith? Taking the monolith and breaking it up into microservices.

Enter the Microservice

Let’s take the monolith example from above and convert it to use microservices. In that case, the application architecture would change to look like this:

There are a few key takeaways from this re-architecture:

  • The broken out sections of the business logic, each encompassing a microservice. Instead of having a single boundary for the entire application, the application is broken into pieces. The complexity of the application is reduced, as the different services have well-defined interactions with each other. For example, this allows for the capability to assign align teams to each individual service, encompassing responsibility in an abstracted piece.
  • The UI layer from before only needs to interface with the customer and event microservices, removing a dependency for the billing microservice on the UI.
  • The billing microservice does not need to store data, so it doesn’t have a data access layer or a database. Instead, it interacts and processes data directly from both the customer and event microservices.

With this kind of architecture comes a whole host of advantages:

  • It’s easier to separate concerns. These boundaries between areas help with development (you only need to concern yourself with your microservice, not the entire application) and with understanding the architecture of the application.
  • Unlike with a monolith, a microservice can use a different tech stack as needed. Considering rewriting everything in a new language? Just change one microservice to use the new tech stack, assess the benefits gained, and determine whether to proceed.
  • Deployments of the application as a whole become more focused. Microservices give you the flexibility to deploy different services as needed.

In the example above, notice the API sitting alongside the other portions of the microservice? We’ll get into that. It’s finally time to talk about the differences between APIs and microservices.

The Difference Between APIs and Microservices

Here are the main differences between APIs and microservices:

  • An API is a contract that provides guidance for a consumer to use the underlying service.
  • A microservice is an architectural design that separates portions of a (usually monolithic) application into small, self-containing services.

By definition, this means an API is usually a portion of a microservice, allowing for interaction with the microservice itself. Another way to think about this is that the API serves as a contract for interactions within the microservice, presenting the options available for interacting with the microservice.

However, if we look at the microservices diagram above, we can see that each microservice is built slightly differently based on its needs. Here are a few examples of different functions a microservice can have:

  • Providing CRUD operations for a particular entity type, such as a customer, event, etc. This service would hold the ability to persist data in a database.
  • Providing a means to accept parameters and return results based on (potentially intense) computations. The billing microservice above may take information on an event or customer and return the billing information required, without needing to store data.

With the above example, you can probably see that a microservice is capable of being more than just an API for a system. An entire application can encompass a series of microservices that use their own APIs for communication with each other. In addition, each of these microservices can abstract its own functionality, drawing logical boundaries for responsibility in the application and separating concerns to make for a more maintainable codebase.

Conclusion

Hopefully now you have a better understanding of what both APIs and microservices are. Code maintainability and quality are both key parts of a successful IT strategy. Microservices help you stay true to them.  They keep your teams agile and help you meet customer demands by producing high-quality, maintainable code.

Are you working in a monolith codebase? Think about taking a portion of that monolith and moving it into a microservice of its own. Once you do that, you should be able to see the benefits of using microservices. In fact, you might even decide to convert the entire thing.

]]>