Products

Solutions

Resources

Search for API Security Tests

REST API

In this section you will learn about REST APIs, what they are, their benefits and drawbacks with some real world examples.

In this section you will learn about REST APIs, what they are, their benefits and drawbacks with some real world examples.

Luke Stephens

Luke Stephens

Luke Stephens

What is a REST API?

Representational State Transfer (REST) is a software architecture that provides guidelines for API design. APIs adhering to REST are termed as REST APIs or RESTful APIs.

At its heart, REST is a set of principles that provide guidelines for designing networked applications. These principles are devised to make applications more scalable and easier to maintain. When APIs adhere to these principles, they are often termed as RESTful APIs.

What is REST API?

Origins of REST

It was introduced and defined in 2000 by Roy Fielding in his doctoral dissertation. Fielding was one of the principal authors of the HTTP specification versions 1.0 and 1.1.

In his dissertation, Fielding proposed REST as an architectural approach to designing networked applications. He contrasted it with other prevalent approaches of the time, notably SOAP (Simple Object Access Protocol), highlighting the benefits of a stateless, client-server model that operates over the HTTP standard.

Principles of REST

  • Uniform Interface: One of the most lauded aspects of REST, this principle promotes a standard way of interacting with a given API. By providing a consistent interface, REST ensures that regardless of the underlying system, the way you interact remains uniform. For instance, whether you're interacting with an API, managing products in an e-commerce platform or one that handles user data in a social media application, the methods to create, retrieve, update, or delete data remain largely consistent.

    For example, when accessing a list of books in a library website, the URL might look something like this: GET /api/books. Similarly, when accessing a list of tasks in a to-do list API, the request might be GET /api/tasks. We’ll dive deeper into how one might perform other tasks such as deleting and editing later.

  • Client-Server Architecture: REST employs a client-server model. The client is responsible for the user interface and user experience, and the server is responsible for storing and retrieving data. This separation of concerns simplifies component implementations, improves scalability, and allows the components to evolve independently.

  • Statelessness: REST emphasizes that each request from a client to a server should be treated in isolation. This means every request should contain all the information needed for its processing without relying on any stored context on the server. This means that every request to the server should contain:

    • The full endpoint and HTTP verb, including the resource identifier, e.g. PUT /api/books/14

    • Any authentication tokens that are required, e.g. Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1

  • Layered System: In a layered architecture, a client interacts only with the adjacent layer without knowing the intricate details of other layers in the hierarchy. This modularity means you can upgrade, scale, or modify one layer without affecting others, which is crucial for scaling systems over time.

  • Cacheability: Caching ensures that frequent and recent requests are served faster by storing data from previous requests. In a RESTful system, the server can explicitly labels responses as cacheable or non-cacheable, ensuring timely data delivery while preserving the system's integrity.

Why REST? Benefits and Drawbacks

Benefits:

  • Simplicity: Uses standard HTTP methods and status codes, making it easy to understand and implement.

  • Scalability: Its stateless nature means it scales out, allowing for more significant distribution and load-balancing.

  • Performance: With proper caching, REST can provide fast responses leading to a better user experience.

  • Language and Platform Agnostic: Can be consumed by any client that understands HTTP and can parse the data format, typically JSON or XML.

Drawbacks:

  • Statelessness Overhead: Every request must contain all information, leading to larger payloads if not managed properly.

  • Lack of Real-Time: Traditional REST is request-response, not well-suited for real-time applications.

  • Multiple Requests: Some operations might require multiple round trips, potentially affecting performance.

How do RESTful APIs Work?

Below you will find a typical lifecycle of a RESTful API operation:

Client Sends a Request

This begins when a user action triggers the client application, such as clicking on a button to view a product list in an e-commerce app. The request might look something like this:

PUT /api/books/14 HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length:length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1

author=15&title=The%20Wind%20in%20the%20Willows

Server Authenticates the Client

Before processing, the server validates the client's identity. It checks tokens or API keys to ensure the client has the right permissions. For instance, banking apps use authentication to ensure only authorized users can check account balances.

In the example above, the server would check the token from the Authorization header, to ensure that it is a valid token and determine which user it belongs to. This authorization header uses Basic authentication.

Server Processes the Request

Depending on the type of request, the server might retrieve, update, delete, or add data. It communicates with databases, processes data, and prepares a relevant response.

In the example above, the server would update the book with ID 14 to have the title The Wind in the Willows, and also associate that book with the author of ID 15.

Server Sends a Response to the Client

The response typically includes data (in formats like JSON or XML) that the client application can interpret and display to the user.

In this instance, the server would most likely respond with a 200 OK response code and a JSON representation of the book in the response body, for example:

{
    "id": 14,
    "title": "The Wind in the Willows",
    "author": {
        "name": "Kenneth Grahame",
        "dob": "1859-03-08"
    }
}

Components of a RESTful API Request

Each API request is likely to contain these components:

  • Unique Resource Identifier (URI): Typically a URL specifying the resource path. For example: /api/books/14

  • Method: Common HTTP methods include GET (retrieve data), POST (send data), PUT (update data), and DELETE (remove data).

  • HTTP Headers: Metadata about the request. This can include the User-Agent, various authorization headers, caching information, and much more!

  • Body: The information that is used to pass additional data to narrow down or customize the request. For example: { "title": "Dune", "author": "Frank Herbert" }

  • Query Parameters: Parameters are the bits after the ? in a URL. For example in GET /api/books?author=15, the parameter name author has been set to 15. This might be used to filter the books that are written by the author with an ID of 15.

RESTful API Authentication Methods

To ensure security, RESTful APIs may use authentication methods such as:

  • HTTP Authentication:

    • Basic: Transfers a base64-encoded string that combines the username and password. This is generally considered to be less secure since it can be easily decoded by anyone who can view the request.

    • Bearer (token-based): More secure than Basic, it provides the client with a token after initial login, which is used for subsequent requests. Bearer tokens are most often combined with JWTs, which are signed tokens that have additional security mechanisms built in.

  • API Keys: These are unique identifiers given to developers. While they offer easy control, they aren't the most secure as they can be shared or exposed.

  • OAuth: A robust method, OAuth, especially OAuth 2.0, provides tokens after a more complex initial authentication, ensuring a higher security level. Platforms like Google and Facebook employ OAuth for their APIs. OAuth is used extensively, but is quite complex to implement.

Components of a RESTful API Response

When a server sends back a response, it isn’t just the data; the response also provides meta-information that aids in understanding the context and status:

  • Status Code: A numeric code indicating the result of the request. Example: 200 means OK/success, 404 means the resource wasn't found, and 500 indicates a server error.

    The status line is always the first line in a HTTP response, for example, this curl command returns a 200 response from example.com, the full line reads HTTP/1.1 200 OK:

~$ curl -I example.com
HTTP/1.1 200 OK
Accept-Ranges: bytes
Age: 500374
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Mon, 09 Oct 2023 20:30:58 GMT
Etag: "3147526947"
Expires: Mon, 16 Oct 2023 20:30:58 GMT
Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
Server: ECS (laa/7B8E)
X-Cache: HIT
Content-Length: 1256
  • Headers: Headers provide meta-information about the response. Example: Content-Length might indicate the size of the response body.

  • Body: It's the main content of the response, often in JSON format. Example: In response to a GET /books/12 request, the body might be: { "id": 12, "title": "Dune", "author": "Frank Herbert" }

  • Status Message: A brief message corresponding to the status code.

    • Example: For a status code of 200, the status message is "OK".

Example of an API Request and Response

Example of a REST API

Understanding the practical application of any concept often requires diving into a tangible, real-world example.

Enter the world of REST APIs via the virtual gateway of a commonly used application: The "To-Do List."

Almost everyone has encountered a "To-Do List" application at some point. These tools are simple yet crucial in helping manage daily tasks and ensuring productivity. From a software perspective, the back end of such an app involves storing, retrieving, updating, and deleting tasks - operations aptly handled by a RESTful API.

API Endpoints in Action

For our To-Do List API, the REST API defines several endpoints, each corresponding to a specific action:

  1. GET /tasks: Viewing All Tasks

    This endpoint provides a comprehensive list of all tasks stored in the application's database.

  2. POST /tasks: Adding a New Task

    Through this endpoint, users can add new tasks, ensuring they don’t forget that important activity they intended to do.

  3. GET /tasks/{taskId}: Accessing a Specific Task

    Sometimes, you might want to view the details of a specific task, especially if additional details like descriptions or due dates are attached. This endpoint serves that purpose.

  4. PUT /tasks/{taskId}: Updating a Task

    Plans change, and so do tasks. Whether it's renaming a task or updating its status, this endpoint ensures adaptability.

HTTP Requests and Responses

The heart of any REST API lies in its ability to manage HTTP requests and deliver appropriate responses. Clients interact with the REST API by making HTTP requests. For example, a GET request to /tasks would retrieve all tasks. The server would respond with a JSON object containing all tasks.

Viewing All Tasks: GET Requests

To retrieve all tasks, the client makes an HTTP GET request:

GET /tasks HTTP/1.1
Host: example.com

The server then processes this request, accessing its database, and formulating a response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "tasks": [
    {
      "id": 1,
      "title": "Buy groceries"
    },
    {
      "id": 2,
      "title": "Walk the dog"
    }
  ]
}

Adding a New Task: POST Requests

Similarly, a POST request to /tasks would create a new task. The request body would contain the details of the new task.

When adding a new task, the client sends a POST request with the new task's details:

POST /tasks HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "title": "Clean the house"
}

Recognizing the creation of a new resource, the server acknowledges and indicates where this new task resides:

HTTP/1.1 201 Created
Location: /tasks/3

Modifying an Existing Task: PUT Requests

Updating a single task can be done by using the PUT HTTP verb. For modifications, like changing the title or updating a task's status, a PUT request is used:

PUT /tasks/1 HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "title": "Finish the report",
  "status": "In Progress"
}

The server confirms the changes and reflects them in its response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "id": 1,
  "title": "Finish the report",
  "status": "In Progress"
}

Conclusion

REST APIs are a popular way to create web services. They use HTTP requests to GET, PUT, POST and DELETE data. RESTful web services use HTTP requests to perform operations on resources. By understanding the basics of REST APIs, you can create web services that are easy to use and maintainable.

On this page

Protect your APIs from attacks now

Protect your APIs from attacks now

Protect your APIs from attacks now

Explore more from Akto

Blog

Be updated about everything related to API Security, new API vulnerabilities, industry news and product updates.

Events

Browse and register for upcoming sessions or catch up on what you missed with exclusive recordings

CVE Database

Find out everything about latest API CVE in popular products

Test Library

Discover and find tests from Akto's 100+ API Security test library. Choose your template or add a new template to start your API Security testing.

Documentation

Check out Akto's product documentation for all information related to features and how to use them.