what is mean by rest api in c#
Loading
what is mean by rest api in c#
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Tuhin PaulRank #7 · 71.9K reputationPosted Jul 19, 2025, 3:13 PM EDT
Imagine you're Browse the web. When you go to a website, you're asking a server for information (like a webpage, an image, a video). REST is a set of guidelines or an architectural style for how web services should communicate to make this interaction efficient, stateless, and scalable.
Key principles of REST:
Client-Server Architecture: There's a client (e.g., your web browser, a mobile app, another server) that sends requests, and a server that responds. They are separate and independent.
Statelessness: Each request from the client to the server must contain all the information needed to understand the request. The server doesn't "remember" past requests from that client. This makes servers easier to scale.
Cacheability: Responses from the server can be cached by clients to improve performance.
Uniform Interface: This is crucial. It means there's a standardized way for clients to interact with resources on the server. This involves:
Resources: Everything is treated as a "resource" (e.g., a user, a product, an order). Resources are identified by unique URLs (URIs).
HTTP Methods: Standard HTTP methods (verbs) are used to perform actions on these resources:
GET: Retrieve data (read-only).
POST: Create new data.
PUT: Update existing data (replaces the entire resource).
PATCH: Partially update existing data.
DELETE: Remove data.
Representations: Resources are sent in various formats (representations), most commonly JSON (JavaScript Object Notation) or XML. The client and server agree on the format.
Layered System: A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. This allows for proxies, load balancers, etc.
Example: If you have a REST API for "products":
GET /api/products- Get a list of all products.GET /api/products/123- Get details of product with ID 123.POST /api/products- Create a new product (sending product data in the request body).PUT /api/products/123- Update product with ID 123 (sending all updated product data).DELETE /api/products/123- Delete product with ID 123.Tuhin PaulRank #7 · 71.9K reputationPosted Jul 19, 2025, 3:15 PM EDT
In C#, building or consuming REST APIs typically involves:
1. Building a REST API (Server-Side)
You use C# to create the web service that responds to HTTP requests according to REST principles. The most common framework for this is ASP.NET Core Web API.
ASP.NET Core Web API:
It allows you to define controller classes (e.g.,
ProductsController).Inside these controllers, you create action methods that correspond to HTTP verbs and URIs.
You use attributes (like
[HttpGet],[HttpPost],[Route]) to map HTTP requests to your methods.Your methods then handle the business logic (e.g., interact with a database, perform calculations) and return data, usually as JSON.
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; [Route("api/[controller]")] // Defines the base route for this controller [ApiController] // Indicates this is an API controller public class ProductsController : ControllerBase { private static List _products = new List // In-memory data for demo { new Product { Id = 1, Name = "Laptop", Price = 1200.00m }, new Product { Id = 2, Name = "Mouse", Price = 25.00m } }; // GET api/products [HttpGet] public ActionResult> GetProducts() { return Ok(_products); // Returns 200 OK with list of products } // GET api/products/1 [HttpGet("{id}")] // {id} is a route parameter public ActionResult GetProduct(int id) { var product = _products.FirstOrDefault(p => p.Id == id); if (product == null) { return NotFound(); // Returns 404 Not Found } return Ok(product); // Returns 200 OK with the product } // POST api/products [HttpPost] public ActionResult AddProduct([FromBody] Product newProduct) // [FromBody] indicates data comes from request body { newProduct.Id = _products.Max(p => p.Id) + 1; _products.Add(newProduct); // Returns 201 Created with the new product and a URI to it return CreatedAtAction(nameof(GetProduct), new { id = newProduct.Id }, newProduct); } // DELETE api/products/1 [HttpDelete("{id}")] public IActionResult DeleteProduct(int id) { var product = _products.FirstOrDefault(p => p.Id == id); if (product == null) { return NotFound(); } _products.Remove(product); return NoContent(); // Returns 204 No Content } } public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }2. Consuming a REST API (Client-Side)
You use C# to make HTTP requests to an existing REST API (whether it's built in C#, Java, Python, etc.) and process its responses. The primary class for this is
HttpClient.HttpClient:This class is part of the .NET Framework / .NET Core and is used to send HTTP requests and receive HTTP responses from a resource identified by a URI.
It's generally recommended to create a single
HttpClientinstance and reuse it throughout your application for better performance and resource management.using System; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; // Often used for JSON serialization/deserialization public class ApiClient { private static readonly HttpClient _httpClient = new HttpClient(); // Reuse HttpClient public static async Task GetProductsAsync() { try { string apiUrl = "http://localhost:5000/api/products"; // Replace with your API URL HttpResponseMessage response = await _httpClient.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); // Assuming you have a Product class that matches the API's Product structure var products = JsonConvert.DeserializeObject>(jsonResponse); Console.WriteLine("Products fetched successfully:"); foreach (var p in products) { Console.WriteLine($"ID: {p.Id}, Name: {p.Name}, Price: {p.Price}"); } } else { Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}"); } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } } // Example for POST public static async Task AddProductAsync(Product newProduct) { string apiUrl = "http://localhost:5000/api/products"; string jsonContent = JsonConvert.SerializeObject(newProduct); var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json"); HttpResponseMessage response = await _httpClient.PostAsync(apiUrl, content); if (response.IsSuccessStatusCode) { Console.WriteLine("Product added successfully!"); } else { Console.WriteLine($"Error adding product: {response.StatusCode}"); } } // Main method to run client example public static async Task Main(string[] args) { // Make sure your API (e.g., the ASP.NET Core Web API example above) is running // before executing this client code. await GetProductsAsync(); // await AddProductAsync(new Product { Name = "Keyboard", Price = 75.00m }); } }REST API in C# means you're either using ASP.NET Core Web API to build web services that communicate using HTTP methods and standard data formats (like JSON) to interact with resources, or you're using
HttpClientin C# to interact with (consume) such services.