DEV Community

Cover image for Send postcards with C# and Flurl
Lob
Lob

Posted on • Edited on • Originally published at lob.com

Send postcards with C# and Flurl

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:‍

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:

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

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

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

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:

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.

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

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.

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.

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

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

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

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.

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

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

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:

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.

Top comments (0)