REST API
Introduction
REST (Representational State Transfer) is a popular architectural style for building APIs. In this tutorial, we will cover how to create and consume REST APIs using .NET. We will create a RESTful service and a client to consume this service.
Prerequisites
- Visual Studio installed with .NET development workload
- Basic knowledge of .NET and C#
Creating a RESTful Service
First, create a new RESTful service project in Visual Studio:
- Open Visual Studio and click "Create a new project".
- Select "ASP.NET Core Web Application" and click "Next".
- Set the name and location for your project and click "Create".
- Choose "API" as the template and click "Create".
Defining the Data Model
Define your data model by creating a new class:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Creating the Controller
Create a new controller to handle API requests:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace MyApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PersonsController : ControllerBase
{
private static List<Person> persons = new List<Person>
{
new Person { Id = 1, Name = "John Doe", Age = 30 },
new Person { Id = 2, Name = "Jane Doe", Age = 25 }
};
[HttpGet]
public ActionResult<IEnumerable<Person>> Get()
{
return persons;
}
[HttpGet("{id}")]
public ActionResult<Person> Get(int id)
{
var person = persons.FirstOrDefault(p => p.Id == id);
if (person == null)
{
return NotFound();
}
return person;
}
[HttpPost]
public ActionResult<Person> Post([FromBody] Person person)
{
persons.Add(person);
return CreatedAtAction(nameof(Get), new { id = person.Id }, person);
}
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Person updatedPerson)
{
var person = persons.FirstOrDefault(p => p.Id == id);
if (person == null)
{
return NotFound();
}
person.Name = updatedPerson.Name;
person.Age = updatedPerson.Age;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var person = persons.FirstOrDefault(p => p.Id == id);
if (person == null)
{
return NotFound();
}
persons.Remove(person);
return NoContent();
}
}
}
Running the Service
Run the service by pressing F5
or clicking the "Start" button in Visual Studio. The API will be available at https://localhost:5001/api/persons
.
Creating a REST Client
Now, create a new .NET Console App to consume the REST API:
- Open Visual Studio and click "Create a new project".
- Select "Console App (.NET Core)" and click "Next".
- Set the name and location for your project and click "Create".
Consuming the REST API
Modify the Program.cs
file to call the REST API:
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
namespace MyRestClient
{
class Program
{
static async Task Main(string[] args)
{
using var client = new HttpClient();
// GET all persons
var persons = await client.GetFromJsonAsync<Person[]>("https://localhost:5001/api/persons");
foreach (var person in persons)
{
Console.WriteLine($"{person.Id} - {person.Name} - {person.Age}");
}
// GET person by id
var personById = await client.GetFromJsonAsync<Person>("https://localhost:5001/api/persons/1");
Console.WriteLine($"{personById.Id} - {personById.Name} - {personById.Age}");
// POST a new person
var newPerson = new Person { Id = 3, Name = "Sam Smith", Age = 40 };
var response = await client.PostAsJsonAsync("https://localhost:5001/api/persons", newPerson);
Console.WriteLine($"Created: {response.StatusCode}");
// PUT to update a person
newPerson.Name = "Samuel Smith";
response = await client.PutAsJsonAsync("https://localhost:5001/api/persons/3", newPerson);
Console.WriteLine($"Updated: {response.StatusCode}");
// DELETE a person
response = await client.DeleteAsync("https://localhost:5001/api/persons/3");
Console.WriteLine($"Deleted: {response.StatusCode}");
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
Running the Client
Run the client application by pressing F5
or clicking the "Start" button in Visual Studio. You should see the details of the persons retrieved from the REST API and the results of the POST, PUT, and DELETE operations.
Conclusion
In this tutorial, we covered how to create and consume REST APIs with .NET. You learned how to define a data model, implement the service in .NET, and consume the service with a .NET client application. REST provides a simple and standardized way to work with APIs, making it easy to build and consume web services. Happy coding!