Advantages of using REST over simple URL and view

2019-05-11 12:45发布

问题:

It might be a silly question for many, but why can't I instead

  • Create a view in django that takes a request and returns HttpResponse in, say, JSON format
  • Map the view to a URL
  • Hit the URL from my browser or another server and use the result?

Thanks.

EDIT - Two approaches: Import some djangorestframework or tastypie and build an api in my application which will throw json responses VS building a class based view and tell it to return json response. Is there any huge advantage of using the first one?

回答1:

I think you could make the same argument about any extension library. It just depends on how much you want to rebuild and what the existing library has that would be beneficial to your project.

Many times I've created custom endpoints without an API library when working with ajax requests inside my project. For that instance, using an API package is overkill. But for having a full API server, Django rest framework offers a lot of functionality.

Sure, you can make views that do what you suggested. But at some point are you going to want to authenticate through an HTTP request? Are you going to want to filter? Are you going to want to make permissions, or just have all endpoints open? Are you going to want to protect against CORS?

You can kind of go down the list of all the features of an API library and ask these questions about what you want to accomplish with your project. If you're working with any type of external application and your django project is just for an API server, usually it's best to go with Rest Framework. If you just have some one-off endpoints to receive ajax requests, usually you just want to build custom endpoints.