Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Start Guide to Create a RESTful Web API in ASP.NET Core

DZone's Guide to

Quick Start Guide to Create a RESTful Web API in ASP.NET Core

Here are the quick and easy steps to get a RESTful web API up and running with Visual Studio.

· Integration Zone
Free Resource

Today’s data climate is fast-paced and it’s not slowing down. Here’s why your current integration solution is not enough. Brought to you in partnership with Liaison Technologies.

As ASP.NET MVC and web APIs are almost same, Microsoft combined both in its ASP.NET Core platform and made it more featured and powerful. Earlier, we discussed How to quickly configure MVC in ASP.NET Core from scratch and view injection using inject in ASP.NET Core MVC. They are more focused on the ASP.NET Core MVC. In this post, we will create simple web API (REST) and test it from the browser.

Let's begin!

In Visual Studio, create a new project (File > New > Project), and select ASP.NET Core Web Application (.NET Core).

Image title

Enter a name of the application CoreWebAPI and click OK.

In the dialog box, select the Web API template and click OK. This will generate default ASP.NET Core WEB API project.

Image title


Let's see what has been changed in the project.json file.

As ASP.NET Core provides a common platform for MVC and web APIs, it will include Microsoft.ASPNetCore.MVC instead of its own web API dependencies.

 "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0"
  }


Once we create a web API project, it will generate default ValuesController, which has default Get, Put, Post, and Delete actions. We will ignore it and create our own API controller.

The setup is over, so let's create new API to expose the data from API call.

Add a Controller Class

In solution explorer, right click on Controllers folder, Add > New Item. Select web API controller class. Enter the controller name ProductController and tap Add.

Image title

Visual Studio scaffolds default actions whenever we create a new web API Controller Class.

[Route("api/[controller]")]
public class ProductController : Controller
{
    // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}


If you had observed, API Controller is inheriting the Controller base class instead of APIController. (only ASP.NET Core has guts to make it happen).

Add a Model Class

Add a new folder in the project named "Models". Now, right-click on the Models folder Add > Class. Name the class Product and click Add.

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public DateTime CreatedDate { get; set; }
}


Add a Service Class

In the solution explorer, right-click on the Models folder and Add >Class. Name the class ProductService and tap Add. ProductService class has method GetProducts that returns a list of products.

public static List<Product> GetProducts()
{
    return new List<Product>()
    {
        new Product {ProductId=1, Name="Product 1",Price=100,CreatedDate=DateTime.Now },
        new Product {ProductId=2, Name="Product 2",Price=200,CreatedDate=DateTime.Now },
        new Product {ProductId=3, Name="Product 3",Price=300,CreatedDate=DateTime.Now },
        new Product {ProductId=4, Name="Product 4",Price=400,CreatedDate=DateTime.Now },
        new Product {ProductId=5, Name="Product 5",Price=500,CreatedDate=DateTime.Now },
    };
}


Routing 

ASP.NET Core introduces new attribute-based routing tokens such as [controller] and [action]. These tokens are replaced at runtime with the name of the controller or action, respectively to which the attribute has been applied. This will reduce the hard-coded route attribute parameters in controllers.

[Route("api/[controller]")]


[controller] will automatically be replaced with the controller name at run time.

Attribute-based routing has also introduced with the various [Http{Verb}] attributes, so you can succinctly state that a GET request with and ‘id’ will be handled by the Get method.

[HttpGet("{id}")]
public string Get(int id)
{
    return "value";
}


To return a list of products from the WebAPI controller, replace the Get() action with the code below. ProductService.GetProducts() will return a list of products.

[HttpGet]
public List<Product> Get()
{
    return ProductService.GetProducts();
}


As Shawn Wildermuth described in his article, this will work, but it makes it difficult to handle errors. IActionResult is a more preferable abstract base class because it has the flexibility to handle all return types.

Run It!

Once we build the project, run it with IIS Express. It will run in a browser and look like below:

Image title


This will display a list of products in JSON. You can prefer other tools like Postman, Fiddler, etc.

Is iPaaS solving the right problems? Not knowing the fundamental difference between iPaaS and iPaaS+ could cost you down the road. Brought to you in partnership with Liaison Technologies.

Topics:
web api ,asp.net core

Published at DZone with permission of Bhavik Patel. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}