Search code examples
mongodbapinosqlrestful-architecture

RESTful API naming convention


I have two collections: persons and pets. A person may have as many pets as they want.

Person document:

person {
  id: person-id
  data: person-info
}

Pet document:

pet {
  id: pet-id
  data: pet-info
  personId: person-id
}

This is my API naming design

  • GET all pets from a person: /api/pets/:personId
  • GET all pets with condition: /api/pets/:personId?age_greater_than=4
  • POST create new pet: /api/pets with the request body that contains person-id
  • PUT update pet info: /api/pets/:petId with the request body that contains person-id and updated info
  • DELETE delete pet: /api/pets/:personId with request body that contains pet-ids

Is there something wrong with my API naming convention and how can this be improved? I think that passing person-id directly to /api/pets is kind of weird.


Solution

  • Naming conventions can be found here: https://restfulapi.net/resource-naming/

    Please also check again HTTP methods and REST. Basic concept is that URLs represent resources and HTTP methods you apply to those URLs indicate what you want to do with those resources.

    GET - Read resource(s) PUT/POST - Create resource(s) PATCH - Update resource(s) DELTE - Delete resource(s)

    So maybe you could use PATCH instead of PUT for updating resources if you only change a part of the resource's attributes.

    Also in the DELETE example you should use the pet id as path variable and not person id.

    For getting all pets of a person, I think /api/person/id/pets could be more straightforward as /api/pets/personid because when you see the URL /api/pets/23 you don't know if it is pet 23 or all pets of person with id 23.

    Think about the best practices again (just use a search engine of your choice) ;)