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.
To create a REST API, you'll need to follow these steps:
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 });
}
}
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);
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?