Skip to content

REST API

Sann Lynn Htun edited this page Nov 23, 2024 · 2 revisions

What-is-an-API

What is a REST API?

A REST API (Representational State Transfer Application Programming Interface) is an architectural style for designing networked applications. It enables communication between different software systems over the internet using standard HTTP methods.

What does it include?

  1. Resources:

    • The fundamental units that REST APIs work with. Each resource is identified by a URL (Uniform Resource Locator).
    • Example: In a book store API, a book might be accessed at /books/{id}.
  2. HTTP Methods:

    • GET: Retrieve data from the server (e.g., get a list of books).
    • POST: Send data to the server to create a new resource (e.g., add a new book).
    • PUT: Update an existing resource (e.g., update book details).
    • DELETE: Remove a resource from the server (e.g., delete a book).
  3. Stateless Communication:

    • Each request from a client to the server must contain all the information needed to understand and process the request. The server does not store any state about the client session.
  4. Client-Server Architecture:

    • The client (usually the front-end) and the server (back-end) operate independently. The client handles the user interface, while the server manages data storage and processing.
  5. Representation of Resources:

    • Resources can be represented in various formats, typically JSON (JavaScript Object Notation) or XML (eXtensible Markup Language).
    • JSON is more widely used due to its simplicity and ease of use with JavaScript.
  6. HATEOAS (Hypermedia as the Engine of Application State):

    • A constraint of REST that allows clients to interact with the application entirely through hypermedia links provided dynamically by the server.

What is it used for?

REST APIs are used for:

  • Web Services: Allowing different web applications to communicate with each other.
  • Mobile Apps: Enabling mobile applications to communicate with servers for data retrieval and manipulation.
  • Microservices: Facilitating communication between different microservices in a distributed architecture.
  • IoT Devices: Enabling internet-connected devices to interact with servers and each other.

Common Useful Notes or Tips and Tricks

  1. Meaningful Resource Names:

    • Use nouns for resources (e.g., /users, /orders), avoid verbs in URIs.
  2. Versioning:

    • Manage API changes by versioning (e.g., /v1/users). This helps avoid breaking existing clients.
  3. HTTP Status Codes:

    • Use appropriate HTTP status codes to indicate the outcome of requests (e.g., 200 for success, 404 for not found, 500 for server error).
  4. Pagination and Filtering:

    • For large datasets, implement pagination and filtering to improve performance and usability (e.g., /books?page=2&limit=10).
  5. Security:

    • Implement authentication and authorization mechanisms like OAuth or API keys to protect your API.
  6. Documentation:

    • Provide clear and comprehensive documentation for your API, including endpoints, request/response formats, and examples.

REST API Explanation Using a Restaurant Analogy

Imagine you're at a restaurant. Here’s how the roles of Customer, Waiter, and Chef map to REST API concepts:

Key Players in the Analogy

Role API Concept
Customer Represents the Client (e.g., web/mobile app).
Waiter Represents the API that bridges the client and server.
Chef Represents the Server (e.g., database, backend logic).

Scenario Walkthrough

1. Customer Makes a Request (GET)

  • Customer (Client): "Can I see the menu?"
  • Waiter (API): Relays the request to the kitchen (server).
  • Chef (Server): Prepares the menu data and returns it to the waiter.
  • Waiter (API): Delivers the menu to the customer.
  • Result: The customer sees the menu.

2. Customer Orders Food (POST)

  • Customer (Client): "I’d like to order a pizza."
  • Waiter (API): Sends the order details to the kitchen (server).
  • Chef (Server): Processes the order, prepares the pizza, and confirms it’s ready.
  • Waiter (API): Returns the prepared food to the customer.
  • Result: The customer receives the pizza.

3. Customer Updates Order (PUT)

  • Customer (Client): "Can you add extra cheese to my pizza?"
  • Waiter (API): Sends the update request to the kitchen (server).
  • Chef (Server): Updates the order and makes the requested change.
  • Waiter (API): Confirms the update with the customer.
  • Result: The customer’s pizza is updated.

4. Customer Cancels Order (DELETE)

  • Customer (Client): "Please cancel my dessert order."
  • Waiter (API): Sends the cancellation request to the kitchen (server).
  • Chef (Server): Removes the dessert from the order list.
  • Waiter (API): Confirms the cancellation with the customer.
  • Result: The dessert order is canceled.

How REST API Concepts Map to This Analogy

Concept Explanation
Resources The menu items (e.g., pizza, pasta) are resources that can be acted upon.
HTTP Methods Actions like GET (view menu), POST (place order), PUT (update order), DELETE.
Stateless Communication The waiter does not remember previous orders; each request carries full details.
Representation The menu/order can be represented in formats like JSON (digital menu).
Client-Server Separation The customer (client) and chef (server) work independently through the waiter.

Code Example Using Restaurant Analogy

1. GET Request: Fetch Menu

// Simulating a GET request to fetch the menu
HttpClient client = new HttpClient();
var response = await client.GetAsync("https://restaurant-api.com/menu");
var menu = await response.Content.ReadAsStringAsync();
Console.WriteLine("Menu: " + menu);

2. POST Request: Place an Order

// Simulating a POST request to place a pizza order
var order = new { Item = "Pizza", Quantity = 1 };
var content = new StringContent(JsonSerializer.Serialize(order), Encoding.UTF8, "application/json");

var response = await client.PostAsync("https://restaurant-api.com/orders", content);
Console.WriteLine("Order Response: " + response.StatusCode);

3. PUT Request: Update an Order

// Simulating a PUT request to add extra cheese to the pizza order
var updatedOrder = new { Item = "Pizza", AddOn = "Extra Cheese" };
var updateContent = new StringContent(JsonSerializer.Serialize(updatedOrder), Encoding.UTF8, "application/json");

var response = await client.PutAsync("https://restaurant-api.com/orders/1", updateContent);
Console.WriteLine("Update Response: " + response.StatusCode);

4. DELETE Request: Cancel an Order

// Simulating a DELETE request to cancel the dessert order
var response = await client.DeleteAsync("https://restaurant-api.com/orders/2");
Console.WriteLine("Cancel Response: " + response.StatusCode);

Summary

In a REST API, the Client (Customer) interacts with the Server (Chef) via the API (Waiter) to:

  1. Fetch data (GET) like retrieving a menu.
  2. Create data (POST) like placing an order.
  3. Update data (PUT) like modifying an order.
  4. Delete data (DELETE) like canceling an order.

This separation ensures clarity, scalability, and stateless communication.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally