Data Visualization with Chart.js and .NET Core API
--
With Chart.js and .NET Core API, you can easily create beautiful charts and graphs that help you analyze and understand your data. In this blog post, we’ll walk you through a step-by-step process of using Chart.js with a .NET Core API to create different types of charts, including pie charts, bar charts, and line charts.
Let’s dive in!
Setting Up the .NET Core API
To get started, we’ll create a simple .NET Core API that returns some data we can use to create charts. Let’s say we’re running a coffee shop and want to track our sales of different products. Our API will return data in the following format:
[
{
"productName": "Coffee",
"totalAmount": 500
},
{
"productName": "Latte",
"totalAmount": 300
},
{
"productName": "Muffin",
"totalAmount": 200
}
]
To create this API, follow these steps:
- Open Visual Studio and create a new project.
- Select “ASP.NET Core Web Application” and click “Next”.
- Name your project and click “Create”.
- Choose the “API” template and click “Create”.
- Open the
Controllers
folder and create a new class calledSalesController
. - Add the following code to the
SalesController
class:
[Route("api/[controller]")]
[ApiController]
public class SalesController : ControllerBase
{
[HttpGet]
public IEnumerable<Sale> Get()
{
return new Sale[]
{
new Sale { ProductName = "Coffee", TotalAmount = 500 },
new Sale { ProductName = "Latte", TotalAmount = 300 },
new Sale { ProductName = "Muffin", TotalAmount = 200 }
};
}
}
public class Sale
{
public string ProductName { get; set; }
public int TotalAmount { get; set; }
}
This code defines a new API endpoint at /api/sales
that returns an array of Sale
objects. Each Sale
object has a ProductName
property and a TotalAmount
property.
7. Run the API by pressing F5 or clicking the “Run” button in Visual Studio.
If everything is set up correctly, you should be able to navigate to https://localhost:XXXX/api/sales
(where XXXX
is the port number your API is running on) and see the JSON data we defined earlier.