Building a Service to Get a City Name from a ZIP Code in .NET Core
Tags: dotnet, beginners, programming, dotnetcore
Published: 2019-09-04 22:37:12

---
title: Building a Service to Get a City Name from a ZIP Code in .NET Core
published: true
description: Have you ever seen one of those dropdowns that populates the city based on what ZIP code you put in? This is a small but neat user interface element, and can be handy for making user input forms simpler and faster to use.
cover_image: https://thepracticaldev.s3.amazonaws.com/i/razgcqc80mo6e2go6cb6.jpg
tags: dotnet, beginners, programming, dotnetcore
series: Getting to know .NET Core
---
*I'm looking for honest feedback on my content. Please comment or [reach out to me on Twitter!](http://bit.ly/2JWE2uV)*

Have you ever seen one of those dropdowns that populates the city based on what ZIP code you put in? This is a small but neat user interface element, and can be handy for making user input forms simpler and faster to use.

## What we'll build

We are going to build an application that takes a ZIP code as an input, and returns city information for that ZIP code that looks like this:

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/1z6xdbphtn8v4fwxjc8j.jpg)

It will be a .NET Core Web API application, that you can use for web pages, mobile, whatever. It's kind of a Microservice but I hate to call it that. It's a simple [RESTful](http://bit.ly/2k0bVBY) application.


## What You'll Need To Get Started

For this tutorial I'm using .NET Core 2.2. You'll need to download the [.NET Core Installer from here](http://bit.ly/2lw4t23). You could easily do this project with a text editor and CLI, but I'm using [Visual Studio](http://bit.ly/2lwzP8K) for this tutorial to show off how easy it is to use.

You should also download [DB Browser](http://bit.ly/2ks648L) for importing data into the SQLite database.

### Step 1: Create a new project.

Load up Visual Studio and create a new project.

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/dvlcm4qtpmp6j1j1imjs.jpg)

Select "ASP.NET Core Web Application" and click next. Name the project whatever you'd like.

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/b0yr5j0y6ektj4drr1oa.jpg)

Next you'll be presented with a screen that looks like this. Select "API" and click "Create".

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/tu174ew6ed5xnvfks4b9.jpg)

This will scaffold out a new API application. The first thing we'll do is delete the "values" controller.

Then, we'll install some tools so we can use SQLite and Entity Framework Core with this application:

At a command prompt or package manager console, run the following:

```
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design
```

This will add SQLite support and the design namespace, which has some design components that will help us out.

The reason we're using SQLite here is that we want something that will be a self-contained database without a server, and run on all the three platforms. SQLite serves this purpose well, at least for small databases like this.

Don't forget to restore the project:

```
dotnet restore
```

*NOTE: EF Core is not required here at all. It would likely be faster with direct access or using something like [Dapper](http://bit.ly/2k4vXvg). But for simplicity we're using EF Core.*

### 2. Create Your Model

Next, create a folder called models, and create a new class. Our class will look like this:

```
public class City
{
	[Key]
    public string Zip { get; set; }
    public float Lat { get; set; }
    public float Lng { get; set; }
    public string CityName { get; set; }
    public string StateId { get; set; }
    public string StateName { get; set; }
    public string TimeZone { get; set; }
    public ICollection<City> Cities { get; set; }
}
```

This class represents the "City" that will be the data type we're working with. As you can see it has the ZIP code, which we're going to use here for an ID. It contains the Latitude/Longitude of the city, name, state id (like OR), state name and time zone.

We'll add a collection for "cities" in here as well for returning a collection of cities. Save the file.

### 3. Define The Context

Next, we're going to create a context for the database that these cities can live in. Create a new class in models that looks like this:

```
public class CityContext : DbContext
{
	public CityContext(DbContextOptions<CityContext> options) : base(options){ }

    public DbSet<City> Cities { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    	optionsBuilder.UseSqlite(@"Data Source=Database/zipcodes.db"); // windows      
    }
}
```

This is the context we'll use for Entity Framework Core so we can easily manipulate the data.

Here we allow the options to be injected in the class, and on configuration we'll override it with an optionsbuilder. This is one place where will direct the context to use a specific file, in this case, **zipcodes.db**. This will be the hosted database with our city information in it.

Next, open up **startup.cs** and add the following lines to the top:

```
using Microsoft.EntityFrameworkCore;
using Zippy.Models;
```
Make sure the 2nd line is a path to your Models namespace (My project is named Zippy).

Then in the Configureservices method, we will add the reference to our database again, and set EF options to use SQLite.

```
	var connection = @"Data Source=Database\zipcodes.db";  // Windows
	services.AddDbContext<CityContext>(options => options.UseSqlite(connection));
```

Notice where it's commented out and says "Windows". If you want to run this application in Linux or OSX you need to reverse the slash so it can be found on the file system:

```
	var connection = @"Data Source=Database/zipcodes.db";  // Linux
```

Now let's create that database.

### 4. Create Our Database

Create a new folder in the project named "Database".

Open up [DB Browser](http://bit.ly/2ks648L) and create a new database.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/of2kbafoye22slhqwerk.jpg)

Create a filename for it to be saved as. You don't need to create any tables or do anything else with it at this time.

### 5. Create a Migration

Our database will only have a single table in it, but we want to create a migration in EF Core for it. Migrations are important for keeping track of historical changes in your database and helping to restore it when needed. Note I'm only talking about schema (layout) information here, not the data stored in it.

```
dotnet ef migrations add Initial
```

Now we have an initial schema setup. Let's update Entity Framework Core:

```
dotnet ef database update
```

Now our database and table are created.

### 6. Import the Data

This will be populated with data from a CSV from [Simple Maps](http://bit.ly/2lCEOEE). If you're planning on using this for a website, make sure and give them credit with a link back to their website.

Now that your table is created we're going to populate it with the data from the CSV file downloaded from Simple Maps. For this project I stripped out some of the columns so it looks like this:

![.NET Core Tutorials](https://thepracticaldev.s3.amazonaws.com/i/y5ig2lbpsgql3oxgc2y7.jpg)

As [Derek](https://dev.to/dinsmoredesign) pointed out, you will need to add a blank field at the end so it matches the columns in your EF generated table. 

Now it's ready to be imported.

Go to file -> import -> table from CSV File:

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/emz42ombazw0bt4ug7u7.jpg)

Load up the CSV file you created earlier. It should look like this:

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/lb0au1uywv4x92dnxiii.jpg)

And import the file. You should now have a fully populated database.

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/0sysgpo9l59xikf30y7n.jpg)

Save the database file. Make sure it's set to be copied with the project.

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/9dh4sbzt40agfvir140l.jpg)

Now let's make our app interact with it.

### 7. Create a Controller

Now we need to create a cities controller. This is a fairly simple process, but Visual Studio makes it even easier.

Right click on your controllers folder and select **add -> controller**

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/d4bdhsib1qiiihg01611.jpg)

We want to select an API Controller with Actions using Entity Framework

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/96sqen6wswnqg67py276.jpg)

Select **City** for the Model class, and **CityContext** for the Data Context Class and generate it.

Visual Studio will generate a set of actions automatically to:

- Get a list of cities in the DB
- Get a particular city from the ZIP
- Add a city
- Remove a city
- Update information

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/wajrntpkqqqrasynqedh.jpg)

While these things are pretty trivial to build, it's nice to have it all scaffolded out. For this to be a useable service you'd want to remove the actions to modify the data, and only keep the GET functionality.


### 8. Set Default Route

The last step is to set our default route. Open up **launchSettings.json** and modify the two lines marked "launchUrl":

Change

```
"launchUrl": "api/values",
```

to
```
"launchUrl": "api/cities",
```

Save the file and build the project. Press F5 to launch it.

### The Finished Product

After pressing F5 you'll see the project come up in your web browser.

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/kucdg2hkgfp1plfol0q2.jpg)

For this service to work as intended, it must take a zipcode as input, this is easily done by appending the zip code to the end of the URL:

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/091emf475ymdfams15b5.jpg)

This looks better when formatted in something like POSTMan:

![.NET Core Tutorial](https://thepracticaldev.s3.amazonaws.com/i/1z6xdbphtn8v4fwxjc8j.jpg)

You could use this service in many ways for a user interface in forms. This is an easy call from a JavaScript application or Mobile app.

### Conclusion

It's really easy to create simple microservices and applications with .NET Core. They are quick to put together and run very fast and lean. Plus, they can run on anything. If you want to learn more about .NET Core check out [some of these great courses](http://bit.ly/2Gsr6Mq) or hit up the [.NET Core help site](http://bit.ly/2lE5ZyR) from Microsoft.

In a future tutorial, I'll show you how to deploy this application to multiple server and cloud environments.

**Note: This application uses data from [Simple Maps](http://bit.ly/2lCEOEE) (free version). If you intend to use this on your site you should give them a link back or consider the professional version as the data will be more accurate and updated.** 

- [Jeremy](http://bit.ly/2JWE2uV)

###What's your .NET Core IQ??

![](https://thepracticaldev.s3.amazonaws.com/i/pv5cvzxdg7qjyxzsfe71.png)

My ASP.NET Core Skill IQ is 200. Not bad, [can you beat it? Click here to try](http://bit.ly/2Gsr6Mq)