0
0
Rest APIprogramming~5 mins

Self link for current resource in Rest API

Choose your learning style9 modes available
Introduction

A self link shows the exact address (URL) of the current resource in an API response. It helps clients know where to find or refresh the same data.

When you want to tell the user or client where to find the current data again.
When building APIs that follow REST rules and want to be easy to navigate.
When you want to help clients update or reload the current resource without guessing the URL.
When you want to provide a clear, clickable link in API responses for the current item.
When you want to support easy linking between resources in your API.
Syntax
Rest API
{
  "_links": {
    "self": {
      "href": "URL_of_current_resource"
    }
  }
}

The _links object groups related links.

The self key holds the URL of the current resource under href.

Examples
This example shows a book resource with a self link pointing to its own URL.
Rest API
{
  "id": 123,
  "name": "Book Title",
  "_links": {
    "self": {
      "href": "https://api.example.com/books/123"
    }
  }
}
This example shows a user resource with a self link to its URL.
Rest API
{
  "userId": 45,
  "username": "johndoe",
  "_links": {
    "self": {
      "href": "https://api.example.com/users/45"
    }
  }
}
Sample Program

This Flask app returns a book resource with a self link showing its own URL. The url_for function builds the full URL dynamically.

Rest API
from flask import Flask, jsonify, url_for

app = Flask(__name__)

# Sample data
books = {
    1: {"title": "Learn Python"},
    2: {"title": "REST APIs Made Easy"}
}

@app.route('/books/<int:book_id>')
def get_book(book_id):
    book = books.get(book_id)
    if not book:
        return jsonify({"error": "Book not found"}), 404
    # Build self link using url_for
    self_url = url_for('get_book', book_id=book_id, _external=True)
    response = {
        "id": book_id,
        "title": book["title"],
        "_links": {
            "self": {"href": self_url}
        }
    }
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always use absolute URLs (full address) for self links so clients can access them anywhere.

Self links help keep API responses consistent and easy to navigate.

Summary

Self links show the URL of the current resource in API responses.

They help clients find or refresh the same data easily.

Use a _links object with a self key holding the URL.