Intro

REST is an architectural style specifically designed for building web services using standard HTTP methods (GET, POST, PUT, DELETE, etc.) and defined by key design principles:

  • Statelessness: No session between the server and client; each request is independent.
  • Uniform Interface: Resources are identified via URIs, and data formats are typically JSON or XML.
  • Client-Server: Separation of client and server concerns.
  • Cacheable: Responses must be explicitly marked as cacheable or not.

REST API Architecture

picture 1

Rest API Queries

A REST API query typically involves sending an HTTP request to a specified endpoint (URL) with certain parameters, headers, and sometimes a body, depending on the type of request being made (GET, POST, PUT, DELETE, etc.).

A REST API query typically includes:

  • An HTTP method (GET, POST, PUT, DELETE)
  • A URL endpoint
  • Request headers (like Content-Type or Accept)
  • An optional request body (for POST and PUT requests)
  • Query parameters (for filtering, searching, etc.)

This structure allows clients to communicate with the server and perform CRUD (Create, Read, Update, Delete) operations on resources effectively.

Here’s a breakdown of what a REST API query might look like for various types of requests:

1. GET Request

This is used to retrieve data from the server.

Example: Fetching a user profile

GET /api/users/123 HTTP/1.1
Host: example.com
Accept: application/json

Example URL:

https://example.com/api/users/123

2. POST Request

This is used to create a new resource on the server.

Example: Creating a new user

POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
Accept: application/json
 
{
  "name": "Alice",
  "email": "alice@example.com"
}

3. PUT Request

This is used to update an existing resource.

Example: Updating user profile

PUT /api/users/123 HTTP/1.1
Host: example.com
Content-Type: application/json
Accept: application/json
 
{
  "name": "Alice Smith",
  "email": "alice.smith@example.com"
}

4. DELETE Request

This is used to delete a resource.

Example: Deleting a user

DELETE /api/users/123 HTTP/1.1
Host: example.com
Accept: application/json

Using a Query Parameter

For example, if you want to search for users by name, you might use a query parameter in a GET request.

Example: Searching users

GET /api/users?name=Alice HTTP/1.1
Host: example.com
Accept: application/json

Example Using Fetch in JavaScript

Here’s how you might make a GET request using the Fetch API in JavaScript:

fetch('https://example.com/api/users/123', {
  method: 'GET',
  headers: {
    'Accept': 'application/json'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

RESTful APIs

A RESTful API is an application programming interface that conforms to the constraints of REST architecture.