API and API Design → What is HATEOAS?

In this episode, I will explain the HATEOAS in API Specifications. You will Learn everything you need to know about HATEOAS and how to create your HATEOAS-enabled RESTful APIs.

In partnership with

Hello “👋”

Welcome to another week, another opportunity to become a Great Backend Engineer.

Today’s issue is brought to you by BoilerPro → Production-ready Next.js and AWS-based SaaS boilerplate, which is all you need to launch your next startup quickly.

Before we get down to the business of today.

I have a special gift for you: You will love this one.

Learn AI Strategies worth a Million Dollar in this 3 hour AI Workshop. Join now for $0

Everyone tells you to learn AI but no one tells you where.

We have partnered with GrowthSchool to bring this ChatGTP & AI Workshop to our readers. It is usually $199, but free for you because you are our loyal readers 🎁

This workshop has been taken by 1 Million people across the globe, who have been able to:

  • Build business that make $10,000 by just using AI tools

  • Make quick & smarter decisions using AI-led data insights

  • Write emails, content & more in seconds using AI

  • Solve complex problems, research 10x faster & save 16 hours every week

You’ll wish you knew about this FREE AI Training sooner (Btw, it’s rated at 9.8/10 ⭐)

Now, back to the business of today.

In this episode, I will explain the HATEOAS in API Specifications. You will Learn everything you need to know about HATEOAS and how to create your HATEOAS-enabled RESTful APIs.

This is from the API and API Design series for backend engineers.

Overview of HATEOAS

HATEOAS is a constraint of REST (Representational State Transfer) that distinguishes it from other network application architectures. According to REST, a client interacts with a network application entirely through hypermedia provided by application servers.

What is HATEOAS?

HATEOAS is an acronym for “Hypermedia as the engine of application state,” which enables a client to dynamically navigate to related resources through hyperlinks embedded in the responses.

Let’s take a look at an API response that illustrates the use of HATEOAS:

{
  "id": 1,
  "title": "Introduction to HATEOAS",
  "author": {
    "name": "John Doe",
    "link": "/authors/1"
  },
  "genre": {
    "name": "Technology",
    "link": "/genres/technology"
  },
  "_links": {
    "self": { "href": "/books/1" },
    "collection": { "href": "/books" },
    "author": { "href": "/authors/1" },
    "genre": { "href": "/genres/technology" }
  }
}

Now, did you see it? Or do you want me to explain further?

You will notice a few differences from the responses above as a backend engineer. However, one notable one is the _links object that contains hyperlinks to other collections.

Each resource now includes _links object, which provides hyperlinks to related resources:

  • "self": Refers to the current resource.

  • "collection": Enlists the endpoint to retrieve all books.

  • "author": Provides a link to the author's resource.

  • "genre": Provides a link to the genre's resource.

HATEOAS helps RESTful interaction to be driven by hypermedia rather than out-of-band information because each response from a HATEOAS-enabled API contains the media types used for these representations and the link relations they may contain.

This allows the client to discover subsequent requests and collections from each response. A client transitions through application states by selecting from the links within a representation or manipulating the representation in other ways afforded by its media type.

Let’s explore some key characteristics of HATEOAS to help us understand better.

Key Characteristics of HATEOAS

  1. Self-descriptive Messages: Every response includes links guiding how to move to the next state, giving the client enough information to know what actions are possible next.

  2. Dynamic Navigation: Clients can dynamically navigate through resources by following links in the responses.

  3. Decoupled Client and Server: Clients do not need prior knowledge of the structure of the service URLs. The server controls the interactions by providing URLs. Hence, it reduces the tight coupling between client and server, making the API more flexible.

Create an HATEOAS REST API

This implementation will be for Node.js using the Express framework. However, for PHP Laravel users, it’s relatively easy to generate a HATEOAS-enabled API quickly, as Laravel has already integrated it. You can read all about it under Eloquent: API Resources.

First, initialize a new project with NPM:

npm init -y
npm install express body-parser

Next, set up a simple RESTful API structure by setting up Express and creating the necessary objects that will be used for the API:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(bodyParser.json());

// Books collection
const books = [
  { id: 1, title: 'Introduction to HATEOAS', author: 1, genre: 'technology' }
];

// Authors collection
const authors = [
  { id: 1, name: 'John Doe' }
];

// Genres collection
const genres = {
  technology: { name: 'Technology' }
};

Next, create your first endpoint and return an object containing both the API object, the media types, and hyperlinks to other objects:

app.get('/books/:id', (req, res) => {
  const bookId = parseInt(req.params.id);
  const book = books.find(b => b.id === bookId);
  
  if (book) {
    const author = authors.find(a => a.id === book.author);
    const genre = genres[book.genre];
    
    res.json({
      id: book.id,
      title: book.title,
      author: {
        name: author.name,
        link: `/authors/${author.id}`
      },
      genre: {
        name: genre.name,
        link: `/genres/${book.genre}`
      },
      _links: {
        self: { href: `/books/${book.id}` },
        collection: { href: '/books' },
        author: { href: `/authors/${author.id}` },
        genre: { href: `/genres/${book.genre}` }
      }
    });
  } else {
    res.status(404).send('Book not found');
  }
});

Lastly, do the same for all your APIs and start your Express server at the end:

app.listen(port, () => {
  console.log(`Server running at <http://localhost>:${port}`);
});

HATEOAS adds a significant layer of flexibility and self-documentation to RESTful APIs by embedding hyperlinks within responses. This approach helps create a more dynamic and discoverable system:

  1. Decoupled Architecture: Clients do not need to predefine URL structures, allowing backend modifications without affecting the client application.

  2. Self-Documenting: Hypermedia is built-in documentation that guides the client through available actions and states.

By adopting HATEOAS, you can build more robust and user-friendly APIs that simplify navigation and enhance interoperability.

HATEOAS is an advanced concept within RESTful APIs that promotes dynamic, link-driven interactions between a client and server.

By embedding hyperlinks in resource representations, it allows for simplified client design, increases flexibility, and enables better discoverability of related resources. This enhances the user experience and future-proofs the API against structural changes.

That will be all for this week. I like to keep this newsletter short.

This is from the API and API Design series for backend engineers. You can bookmark it for further reading.

Don’t miss it. Share with a friend

Did you learn any new things from this newsletter this week? Please reply to this email and let me know. Feedback like this encourages me to keep going.

See you on Next Week.

Remember to get BoilerPro now → Production-ready Next.js and AWS-based SaaS boilerplate, which is all you need to launch your next startup quickly.

Top 5 Remote Backend Jobs this week

Here are the top 5 Backend Jobs you can apply to now.

👨‍💻 Sandman Media Inc
✍️ Full stack PHP Developer
📍Remote, Africa
💰 Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 GoTu Technology, Inc.
✍️ Remote Backend Engineer
📍Remote
💰 Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 Pinterest
✍️ Sr. Software Engineer - Backend
📍Remote
💰 Click on Apply for salary details
Click here to Apply for this role.

👨‍💻Toggl
✍️ Remote Senior Backend Engineer
📍Remote
💰 Click on Apply for salary details
Click here to Apply for this role.

Want more Remote Backend Jobs? Visit GetBackendJobs.com

GBE Podcast

In this week’s episode of the Great Backend Engineer (GBE) podcast, I sat down with Anthony Alaribe to discuss the importance of Monitoring and Observability for backend engineers.

Watch on Youtube (subscribe):

Spotify:

Apple Podcast:

Backend Engineering Resources

Whenever you're ready

There are 4 ways I can help you become a great backend engineer:

1. The MB Platform: Join 1000+ backend engineers learning backend engineering on the MB platform. Build real-world backend projects, track your learnings and set schedules, learn from expert-vetted courses and roadmaps, and solve backend engineering tasks, exercises, and challenges.

2. The MB Academy:​ The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

3. Backend Engineering Courses: Access a catalog of backend courses, development courses, advanced backend engineering courses, nests courses, and backend web development courses. Next-level Backend Engineering courses and Exclusive resources.

4. GetBackendJobs: Access 1000+ tailored backend engineering jobs, manage and track all your job applications, create a job streak, and never miss applying. Lastly, you can hire backend engineers anywhere in the world.

LAST WORD 👋 

How am I doing?

I love hearing from readers, and I'm always looking for feedback. How am I doing with The Backend Weekly? Is there anything you'd like to see more or less of? Which aspects of the newsletter do you enjoy the most?

Hit reply and say hello - I'd love to hear from you!

Stay awesome,
Solomon

I moved my newsletter from Substack to Beehiiv, and it's been an amazing journey. Start yours here.

Reply

or to participate.