D
D
Dmitry2016-05-08 06:47:29
API
Dmitry, 2016-05-08 06:47:29

What is the correct way to refer to related objects in REST API?

I can't figure out how to display related objects.
I looked through the GitHab API, made some conclusions, but it seemed to me not rational to implement them ...
Let's say there are 2 models.
Orders

  1. date of creation
  2. Link to client
  3. Link to employee
Clients
  1. date of creation
  2. username
  3. Surname and initials

A piece of the GitHab API
{
    "site_admin": false,
    "name": "The Octocat",
    "company": "GitHub",
    "blog": "http://www.github.com/blog",
}

According to githab i have to do like this
{
    "id": 1,
    "create_at": "2016-04-29T19:37:03Z",
    "client": "client_ login",
    "user": "root"
}

If I need to additionally get USER, then I make a request to the database and get it, OK.
And if I display a list of all orders, and for example there are 100 of them, then to get information about the client, I need 100 requests and 100 on the user ???
I will make a reservation that it is mandatory to request information about these 2 related models.
Thanks to everyone who responded!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Scherbakov, 2016-05-08
@pyHammer

1. Why 100 requests? Let's say you want to ask for a list of all orders.

GET /api/v1/orders/
[{
    "id": 1,
    "created_time": "2016-04-29T19:37:03Z",
    "client": "client_ login",
    "employee": "jane"
}, {
    "id": 2,
    "created_time": "2016-05-29T19:37:03Z",
    "client": "another_client",
    "employee": "john"
}, ...]

It is not clear, by the way, do you have a client, an employee and a user - are they the same or different things? Why are you outputting user in the order if it is a customer property and not an order property? But the essence is the same: either a numeric or a letter identifier is used for external entities.
Now you can make a request for the client you need:
GET /api/v1/clients/another_client/
{
    "id": 1,
    "created_time": "2016-04-29T19:37:03Z",
    "full_name": "Vasya Pupkin",
    "user": "bububum"
}

If you have a relatively small number of clients, there is nothing to worry about. If your number of customers is comparable to the number of orders, you can make a nested entity as follows:
GET /api/v1/orders/
[{
    "id": 1,
    "created_time": "2016-04-29T19:37:03Z",
    "client": {
        "id": 2,
        "full_name": "Vasya Pupkin"
    },
    "employee": "jane"
}, ...]

In general, in fact, in the RESTful API it is supposed to write their URL instead of the id of the entities, but we will leave it out of the brackets. I don't usually do this myself...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question