How do I create and consume REST APIs in C#

Creating and consuming REST APIs in C# is a straightforward process that can be accomplished using various libraries. One of the most popular libraries for this purpose is ASP.NET Core, which provides robust tools for building web APIs. In this guide, we'll look at how to create a simple REST API and how to consume it using an HTTP client.

Creating a REST API with ASP.NET Core

To create a REST API, you'll need to follow these steps:

  1. Create a new ASP.NET Core Web API project.
  2. Define your models.
  3. Set up a controller to handle HTTP requests.
  4. Define routes and actions.

Example: Creating a Simple ToDo API


    using Microsoft.AspNetCore.Mvc;
    using System.Collections.Generic;

    [Route("api/[controller]")]
    [ApiController]
    public class TodoController : ControllerBase
    {
        private static List<string> todos = new List<string> { "Task 1", "Task 2" };

        [HttpGet]
        public ActionResult<IEnumerable<string>> GetTodos()
        {
            return Ok(todos);
        }

        [HttpPost]
        public ActionResult AddTodo([FromBody] string todo)
        {
            todos.Add(todo);
            return CreatedAtAction(nameof(GetTodos), new { todo });
        }
    }
    

Consuming a REST API

To consume a REST API in C#, you can use the HttpClient class. Here's an example of how to call the ToDo API we just created:


    using System;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;

    class Program
    {
        private static readonly HttpClient client = new HttpClient();

        static async Task Main()
        {
            var todos = await client.GetStringAsync("https://localhost:5001/api/todo");
            Console.WriteLine(todos);

            var newTodo = new StringContent("\"New Task\"", Encoding.UTF8, "application/json");
            await client.PostAsync("https://localhost:5001/api/todo", newTodo);
        }
    }
    

REST API C# ASP.NET Core HttpClient Web API .NET API Development Consume REST API