What is Resource in REST API: Simple Explanation and Example
REST API, a resource is any object or data that can be accessed or manipulated through a unique URL. It represents things like users, products, or orders, and the API uses HTTP methods to perform actions on these resources.How It Works
Think of a resource in a REST API like a specific item in a library. Each book (resource) has its own unique spot on the shelf (URL). When you want to read or change a book, you go to its exact place and perform actions like reading, updating, or removing it.
In REST, resources are identified by URLs, and you use HTTP methods like GET (to read), POST (to create), PUT/PATCH (to update), and DELETE (to remove) to work with them. This makes the API easy to understand and use because each resource is clearly defined and accessible.
Example
This example shows a simple REST API resource for a user. The URL /users/1 points to the user with ID 1. You can get the user's data with a GET request.
GET /users/1 HTTP/1.1 Host: example.com Response: { "id": 1, "name": "Alice", "email": "alice@example.com" }
When to Use
Use resources in REST APIs whenever you want to organize and access data clearly and consistently. For example, in an online store, products, customers, and orders are all resources. Each has its own URL and can be created, read, updated, or deleted through the API.
This approach helps developers and applications interact with data in a simple, predictable way, making it easier to build and maintain web services.
Key Points
- A resource is any data or object accessible via a unique URL.
- HTTP methods define actions on resources (GET, POST, PUT, PATCH, DELETE).
- Resources make APIs organized and easy to use.
- Each resource represents a real-world entity like a user or product.