简体   繁体   中英

How to expose a Django model as a RESTful web service?

I'm trying to create a REST web service that exposes the following Django model:

class Person(models.Model):
    uid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=40)
    latitude = models.CharField(max_length=20)
    longitude = models.CharField(max_length=20)
    speed = models.CharField(max_length=10)
    date = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(self):
        return self.name

Here's how I thought about it so far:

Get all Persons
URL: http://localhost/api/persons/
Method: GET
Querystring:

  • startlat=
  • endlat=
  • startlng=
  • endlng=

Used for getting the Persons that are within the specified coordinate range.

  • page=

Used for getting the specified page of the response (if the response contains multiple pages).

Returns:

  • 200 OK & JSON
  • 404 Not Found

Example:
Request:

GET http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60

Response:

{
  "persons":
  [
     { "href": "1" },
     { "href": "2" },
     { "href": "3" },
     ...
     { "href": "100" }
  ],
  "next": "http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60&page=2"
}


Get info on a specified Person
URL: http://localhost/api/persons/[id]
Method: GET
Returns:

  • 200 OK & JSON
  • 404 Not Found

Example:
Request:

http://localhost/api/persons/5/

Response:

{
  "uid": "5",
  "name": "John Smith",
  "coordinates": {
                   "latitude":"14.43432",
                   "longitude":"56.4322"
                 },
  "speed": "12.6",
  "updated": "July 17, 2009, 8:46 a.m."
}



How correct is my attempt so far? Any suggestions are highly appreciated.

{ "href": "1" },

1 is hardly a valid URL. You should use full URLs. Google for HATEOAS .

Also, remember to send a relevant Content-Type header. You may want to make up your own mime-type to describe the format. This gives you the option to later change the content-type (Eg. change the format after publishing). See Versioning REST Web Services

I think query parameters could be simpler and clearer. This would make the URI more readable and would allow more flexibility for future extensions:

GET http://localhost/api/persons/?latitude=10:15&longitude=30:60

You may want to enable these in the future:

GET http://localhost/api/persons/?latitude=10&longitude=60&within=5km

Seems REST-cool. Even i worked on same kind of thing, few days earlier.

The only change, i would love to do in it, is the direct link to the person details. And also some details (like name here) to identify the person, and aid me in decision to navigate further. Like...

{
  "persons":
  [
     { "name": "John Smith", "href": "http://localhost/api/persons/1/" },
     { "name": "Mark Henry", "href": "http://localhost/api/persons/2/" },
     { "name": "Bruce Wayne", "href": "http://localhost/api/persons/3/" },
     ...
     { "name": "Karl Lewis", "href": "http://localhost/api/persons/100/" }
  ],
  "next": "http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60&page=2"
}

This way, i am giving everything, to present data as,

Next Page

It's ok to provide shorthand URIs in your JSON responses if you provide some templating system. Like giving a base URI as something like http://whatever.com/persons/ {id}/ and then providing IDs. Then with python you can just do a format call on the string. You don't ever want to make the programmer actually look at and understand the meaning of the URIs, which isn't necessary when you use templates.

You might want to take a look at pre-existing REST middleware. I know they saved me a lot of time. I'm using http://code.google.com/p/django-rest-interface/ . And a snippet of the urls.py

json_achievement_resource = Collection(
    queryset = Achievement.objects.all(),
    permitted_methods = ('GET',),
    responder = JSONResponder(paginate_by = 10)
)

urlpatterns += patterns('',
    url(r'^api/ach(?:ievement)?/(.*?)/json$', json_achievement_resource),
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM