简体   繁体   中英

Question Regarding API Design

I am in the process of researching the best "design-pattern" a web API. I am currently using Django as my web framework. I created a non-ajax interface that causes the entire page to reload at each request.

Now, I am starting incorporate ajax into the interface. For the sake of this discussion, two example pieces of functionality that I need to add an API for are the following

1) beta page: the user supplies an email address. i want to make an ajax call to the serverside to see if it already exists in my DB. my initial design for this call would be a view function similar to

def check_email(request):
    if request.method == "POST":
           # check db

           # return JSON true/false

2) profile picture uploads, where the new profile picture is added to your page without a full page reload

as far as i can tell, the best way to do this is via a POST call to a view function. then, the response would return JSON, which I can then inject back into the DOM accordingly.

can someone please let me know if I am on the right track with designing this API?

note: i have checked out django-piston, and it seems pretty useful also.

thanks

Yes, you seem to be on the right track. One quibble: to check if an email address exists in the db, you should ideally use a GET rather than a POST, as no information is being updated - you are simply asking if something exists.

One alternative to returning JSON is to return pre-rendered HTML which you can inject directly into the DOM at the appropriate point. The advantage of doing it this way is that you can use Django's template mechanism to render your existing template fragments - the only difference is that you render a fragment in isolation, rather than including/extending it within an entire HTML page.

You're right on track, but I would use request.is_ajax() to check if it's actually a ajax request to return the response accordingly. from the django request docs

Returns True if the request was made via an XMLHttpRequest, by checking the HTTP_X_REQUESTED_WITH header for the string 'XMLHttpRequest'. Most modern JavaScript libraries send this header. If you write your own XMLHttpRequest call (on the browser side), you'll have to set this header manually if you want is_ajax() to work.

This will allow you to separate return values for users that have javascript disabled, allowing them to still use your site correctly. If you're not using a javascript library, you set this yourself.

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