📜 ⬆️ ⬇️

OData REST API - minor tricks (part 1)

The OData protocol has many hidden advantages (although there are enough disadvantages). Starting with this article, we would like to share some small, useful tricks of using the OData protocol.

All further examples use the following simple data scheme.


person properties:

  • id (string)
  • firstname (string)
  • lastname (string)
  • age (number)
  • likes (list of books)

book properties:
')
  • id (string)
  • title (string)
  • author (list of persons)
  • publisher (a company)

company properties:

  • id (string)
  • name (string)
  • president (person)


Test database posted on the databoom.space website
Test data can be viewed using the OData URL samples.databoom.space/api1/sampledb/collections/allobjects

1. How to get an array of objects that someone refers to


Suppose we want to get a list of books that a person likes.
To get a person with id 'person1', we can write
... / persons (person1)

To get the books that this person likes, add the name of the property property to the URL
... / persons (person1) / likes

Now we can go ahead and find all publishers who have published books that person1 likes.
... / persons (person1) / likes / publisher

2. How to get an array of objects that refer to someone


In the previous example, we received a list of books that a person likes with id 'person1'.
Now we want to get all the people who like the book with id 'book2'. Notice the person through the likes property refers to the books he likes, and the books do not refer to people who love them.

To get the book with the id 'book2', we can write
... / books (book2)

We cannot write ... / books (book1) / persons_who_likes - the book has no such property

Then we write
... / books (book1) / _ backlink (likes)

_backlink (likes) is like a back link for the likes link
likes - that love
_backlink (likes) - who likes

In some implementations of OData, it is assumed that the developer must create a pseudo property named for example persons_who_likes and write the handler of such requests. The _backlink operator is not included in the standard, but can sometimes significantly simplify the work.



If you are interested in this post, you can also see our documentation and examples of using the REST API , as well as examples using the JavaScript library

In the next post we will describe how to filter objects based on their interrelations.

Source: https://habr.com/ru/post/262937/


All Articles