2

I'm building a REST Web service and I'd like to what is the best way (performance wise, elegance, and best-practice) on how to structure my resources. I have two models with ManyToMany relationship, so I could design my resources endpoints like follow (and as explained here :

/api/v1/question/{q_id} #to access the question resource

and

/api/v1/question/{q_id}/answers/{a_id} # to access the answers of a question.

Now that's completely fine with a GET method, what if I want to create a new question with new answers, I have to send a POST request to the first URL and then another POST to the second?? Is it still considered a clean way of doing things despite the round trips?

P.S I'm using Django and still hesitating between django-simple-rest, django-rest-framework and django-tastypie with BackboneJS in the client side.

Community
  • 1
  • 1

1 Answers1

1

REST is about resources. There is no best way to do it. I'll give you my Opinion (I run a big API since a long time).

For sake of simplicity I'd just create two resources:

  • Question: /api/v1/question/
  • Answer: /api/v1/answer/

Why? Because it's simple. Now, in order to make it performant and HATEOAS compatible, you could use different alternatives. For example, when you get a question, you could also get a list of answers:

GET /api/v1/question/{q_id}/
{
    'question': 'Should I use REST or SOAP?'
    'created_date': '...',
    'user_id': '99',
    'answers': [
        {
            'answer': 'REST, of course!',
            'user_id': 23,
            'resource_uri': '/api/v1/answers/818/'
        },
        {
            'answer': 'Are you nuts? Use SOAP!',
            'user_id': 12,
            'resource_uri': '/api/v1/answers/915/'
        }
    ]
}

You could use a similar scheme with a POST.

If you use Django Tastypie (which I've had a great sperience with) you could use fields to accomplish this simple task. You could get this working with 50 loc.

Important: Are you sure you have a ManyToMany between answer and question?

santiagobasulto
  • 11,320
  • 11
  • 64
  • 88
  • How would this work with POST in Tastypie with fields? And yes its ManyToMany field as every answer can belong to many questions too. Does it make sense? –  Jun 03 '13 at 07:36
  • Does it make sense? Not really. But it doesn't matter, it's your software and you know the requirements better than me. – santiagobasulto Jun 03 '13 at 10:33
  • With Tastypie: I assume you want to create a question with many answers, all at the same time. In this case you can use the hydrate method. It's totally viable. – santiagobasulto Jun 03 '13 at 10:34