Lob's website experience is not optimized for Internet Explorer.
Please choose another browser.

Arrow Up to go to top of page
Using Lob with C# and Flurl
Engineering
November 16, 2021

Using Lob with C# and Flurl

Author Avatar
by 
Shariq Torres

2022 update for our dotnet fans: Lob has released a C#/.NET SDK; fully generated using an Open Api 3.0 spec. (Repo / Download the package)

At Lob, our mission is to connect the online and offline world. We support developers in this pursuit by providing direct mail and address verification APIs. Today we are diving into C# to show how to easily implement Lob’s API in your ASP.Core application using the Flurl Http Library. Now, there is no particular reason we are using Flurl in this example. You can easily implement Lob API in whatever HTTP client you choose—RestSharp, ServiceStack, etc. We happened to choose Flurl because it’s the latest hotness.

The complete code for this project is available here.

Prerequisites

You will need the following installed:

.Net 5 - installation instructions here.
An IDE, we used VSCode in this tutorial, but Visual Studio works as well.

Getting Started

We’ll start with a simple Razor application and make use of the address and postcard APIs that Lob provides. With this application we’ll do the following:

  1. Save an address to our account’s address book
  2. Create a postcard using the address and preview it.

First, create a project folder by running this command in your terminal.

<script src="https://gist.github.com/ShariqT/9d7facef4fe6b1c96a1e06b7734924ef.js"></script>

This creates a “LobExampleApp” folder to house our code. Change to this directory and run.

<script src="https://gist.github.com/ShariqT/88450202a754f1e2ac7e36a87843eeb4.js"></script>

Pointing your browser to https://localhost:5001 will bring up a welcome message.

If you have trouble getting this screen, here are some troubleshooting docs

The Flurl library is a required dependency. Run the following command in your terminal:

<script src="https://gist.github.com/ShariqT/641ff660e135e7a60a6619cebe05b302.js"></script>

Login to your Lob account and locate your API keys under Settings. If you don’t have an account yet, It's easy to sign up and absolutely no cost to start sending requests.

API keys, database credentials, etc, should be environment variables to avoid hardcoding them into your project. Nothing is worse than pushing a commit and seeing sensitive login information in the repo. To avoid doing this, we make our Lob API key an environment variable in the `Projects/launchSettings.json` file. Simply add a key called “LOB_API_KEY” to the “environmentVariables” section. Here is an example.

<script src="https://gist.github.com/ShariqT/cd9427e618718059820f04a0909ed7cf.js"></script>

Now, let’s create a class that uses our API key to make API requests.

Connect to Lob

The good thing about statically typed languages like C# is that they force us to think about the interaction between our application and external services. We start with a few POCOs (Plain Old C# Objects) that represent messages sent and responses received from Lob API. Making these POCOs helps us when using Flurl to make API calls.

LobModels.cs

<script src="https://gist.github.com/ShariqT/3166d500209e488f0445eb921334d5cb.js"></script>

Note, we add extra annotations in the `AddressResult` class in order to use this model to send requests to Lob. We take advantage of automatic validation included in Razor pages, which will come into play later on.

With our POCOs in place, let’s create a class to handle the interaction between our application and Lob API.

LobConnector.cs

<script src="https://gist.github.com/ShariqT/d8520d7993fff5ebf723277c23d6ecbc.js"></script>

Environment variables from `launchSettings.json` are read and used in each method which corresponds to API endpoints provided by Lob. For example, listAddresses maps to Lob’s address endpoint. Looking closer, you’ll see this pattern repeated across the class.

On line 16, we append the endpoint that we are going to connect to. In this example, we hit the “/addresses” endpoint. On line 17, we authenticate to Lob using Basic Authentication. Our Lob API key is placed where the username would be and we leave the password empty. Flurl sets the basic-auth headers using the WithBasicAuth method. For those using RestSharp it looks like this.

<script src="https://gist.github.com/ShariqT/c4dba54853e30fe5ef6325b9d549b058.js"></script>

A good thing about Flurl is the ability to cast a JSON response into C# objects via POCOs. This functionality is supported in Flurl and RestSharp.

List and save addresses

`LobConnector.cs` holds our app core logic where we create and update data. Let’s connect this core to the rest of the application by altering `Pages/Index.cshtml.cs` (a razor page) with the following code:

LobConnector.cs

<script src="https://gist.github.com/ShariqT/e6693d723998b74db30bfce61cb9fd2c.js"></script>

Razor routes use a convention over configuration approach. `Index.cshtml.cs` corresponds to the C(ontroller) of the MVC paradigm. `Index.cshtml` corresponds to the V(iew) of this paradigm. The model declared in the file is available for use in Index.cshtml. For this reason, we set a property called addresses that is populated with the listAddresses method response from the LobConnector class.

Index.cshtml.cs

<script src="https://gist.github.com/ShariqT/e3da8b8a31c87a489f3a684690fd3df5.js"></script>

We reference the model in `Index.cshtml.cs` on line 2 and check to see if the addresses property has a length longer than 0. If not, we prompt the user to enter an address. If the length is longer than 0, then we list all of the addresses returned, adding a link to preview a postcard. There is a lot going on behind the postcard preview link, but first, let’s focus on adding a new address.

On lines 9 and 36, we reference the ./New route. Remember Razor follows a convention to control routing. This means the framework looks for two files -- New.cshtml and New.cshtml.cs in the same directory as Index.cshtml. Let’s start with the `New.cshtml.cs` file first.

New.cshtml.cs

<script src="https://gist.github.com/ShariqT/be03c2b53878e59ca7c60656ff70f991.js"></script>

On line 20, use a “BindProperty” attribute on the model’s addressResult property. This makes for easy validation on line 25.

“But Shariq, how does Razor know the validation rules?”, you may ask.

Well, let’s take a look at LobModels.cs. at the validation rules we defined when creating the class.

<script src="https://gist.github.com/ShariqT/5262101d63ac6792507bee676baf5e7a.js"></script>

We use `Required` and `StringLength` attributes on several properties letting Razor know the validation rules.

Now, add the following code to the New.cshtml:

New.cshtml

<script src="https://gist.github.com/ShariqT/7fbf5944acd20188975daff783a93552.js"></script>

At this point, you should be able to add and save addresses to your Lob address book. Add a few addresses because, in the next section, we generate a preview of a postcard using these saved addresses.

Create a postcard and preview

For our last step, we generate a preview of a postcard via Lob’s API. We take a couple of query parameters (Variable1 and Variable2, respectively) and merge these into the postcard along with the selected address.

We start by creating `Postcard.cshtml.cs` and adding the code is below:

Postcard.cshtml.cs

<script src="https://gist.github.com/ShariqT/d90b4e120a3ef472b2a5223ebad4a326.js"></script>

On lines 34 and 35, we set the template for the postcard. This is a bare-bones example of a postcard, but feel free to add CSS, images, etc to your own template. You should follow these guidelines to make sure that your template is print-ready.

On lines 39-42, we grab the parameters ( address id, variable1 and variable2) from the query string portion of our url. These were set in Index.cshtml on line 30. On lines 43-48 we gather all of the information into a LobPostcardRequest instance. On line 48, we set the merge variables in order to insert dynamic content into our postcards. We use an anonymous object to pass this info along to the Lob API.

The only task remaining is create `Postcard.cshtml` where we add the following code:

Postcard.cshtml

<script src="https://gist.github.com/ShariqT/107a91a4aebf36599c5d8dc01ca9e25d.js"></script>

This form allows you to set the query variables on this page and trigger a new postcard preview.

Conclusion

You just built a complete C# application using Lob’s API to save addresses and generate postcards from your addresses. This is only a small subset of the functionality available from Lob; you can send checks, letters, self-mailers, and verify addresses using Lob.

If you have any questions, feel free to comment on this article or contact us on Github.

Continue Reading