Lesson Weekend

In this lesson, we'll start building a Cretaceous Park API. This API will share data about a wildlife park consisting of creatures from the cretaceous era that other developers can query.

First, create a new directory called CretaceousPark.Solution. Create a project directory called CretaceousPark inside that directory.

Next, let's go into that directory and create our project.

$ dotnet new webapi --framework net5.0

Let's take a look at the files that the CLI creates for us.

bin
Controllers
obj
Properties
appsettings.Development.json
appsettings.json
Program.cs
Startup.cs
CretaceousPark.csproj
WeatherForecast.cs

The CLI generates many files, including Program.cs, Startup.cs, and a .csproj file. It also generates several boilerplate files, such as a controller with some starter code as well. We will replace this with our own code soon. Note that though the CLI generates our boilerplate, it does not add git tracking to our project. Make sure to initialize git and add a .gitignore file when you create a new API project, and make sure your appsettings.json are in your .gitignore, as per usual. When creating your README, don't forget to instruct users on how to create and populate this file!

We'll make one minor change to our Startup.cs file. Find and comment out the following line:

app.UseHttpsRedirection();

This method causes our server to reroute all traffic to the HTTPS port on our server. This increases application security but it can cause our browser to prevent access to the site and will slow us down when we're developing our project.

Before we move on, let's see what our API is actually doing.

To get more informative responses in our terminal, we need to update the logging settings, in our appsettings.Development.json file. Replace the existing code with the following:

appsettings.Development.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

First, let's start our server with dotnet run.

Now let's open Postman and send a GET request to http://localhost:5000. We'll get a "404 Not Found" status in Postman along with an empty response. If we look at the terminal that is running the API, we should see something like this:

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/1.1 GET http://localhost:5000/ application/json 21
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished HTTP/1.1 GET http://localhost:5000/ application/json 21 - 404 0 - 163.1984ms

This confirms that our API has been queried but has returned a 404 error. This is different than what will happen if we send a bogus request to a server that doesn't exist. If we try sending a GET request to http://localhost:5555, we'll get the following message:

Postman says it can't get a response from the server

When we send a GET request to http://localhost:5000, we are communicating with our local running application. However, the application is telling Postman that it couldn't find any resources at http://localhost:5000.

Let's see what routes are available. When using the dotnet new webapi command, your project comes with a default implementation of Swagger, a package that helps to document your routes. You can view it in the browser, by going to http://localhost:5000/swagger, which will show some boilerplate and a GET route at /WeatherForecast. Go ahead and click Get, then Try it out and Execute.

Underneath, you'll see the Curl command for that route (which would make the same request from the command line), the URL, and a sample response, an array of JSON objects showing data about weather.

Now let's take a look at the controller file that the CLI generated for us:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CretaceousPark.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

The CLI has automatically created a GET route for our boilerplate controller. We can see that if we route to http://localhost:5000/WeatherForecast in the browser, it would return a similar JSON array of objects as we saw returned in Swagger. Note that this response will act the same, whether we are using the browser or Postman.

So what exactly is going on here? How is this different from creating an MVC web application?

The MVC applications we've been creating the last few sections have been serving HTML, which we access through the browser. Instead of serving HTML, this API serves JSON data. APIs use other formats such as XML as well, but JSON is the most common. Instead of navigating to a site via a browser, we use a client such as Postman or another application making an API call to query one of our API's endpoints for data. Developers are then free to use that data in the application as they wish. This makes it much easier for developers to use different types of technology and still communicate freely between two applications. For instance, it doesn't matter if the API application uses C# and .NET and the application making the query uses Ruby and Rails. They can communicate using a standard format (JSON) and there will be no issues related to language incompatibilities.

Before we move on, let's update the launch URL to the GET method of the controller we'll add soon:

Properties\launchSettings.json
"launchUrl": "api/Animals",

Now that we've covered the basics of what the CLI offers, we're ready to start adding our code. Then, we'll look into how to add full CRUD functionality into our project!

Lesson 3 of 22
Last updated April 6, 2022