On 10/01/2009, at 1:38 AM, mk wrote:
>
> Hello everyone,
>
> For the app I'm going to develop, I will need sort of scripting
> "API" to
> it (callable from command line and/or Python or PHP library) in
> addition
> to normal web interface.
>
> On the face of it, it seems straightforward: just put the code like
> following in lib/
>
> def fun(params, web=True):
> ...
>
> ..and call it from controllers, while making scripting API library
> calling fun with web=False.
What does the controller need to do differently for an "API" call vs a
user request? Typically, in the RESTful HTTP world, there is no
difference between them except for the format of the response. A user
driving a browser wants a "pretty" response rendered from HTML/XHTML.
A script wants something easy to parse, such as JSON or XML. HTTP
supports negotiation of response format using the "Accept" header.
Browsers already generate an Accept header indicating that they would
like HTML/XHTML. For requests from scripts, get them to send an
appropriate Accept header for a format your application supports. For
example, if they send "Accept: application/json" then your app can
respond with JSON. Your controller logic typically remains the same
accept for the response rendering (and then you can move that part to
a decorator to keep the controller methods clean).
Pylons (via WebOb) makes this easy by providing a request.accept
object representing the request Accept header. So you can do, for
example:
request.accept.best_match("application/json")
which will return True or False if the client will accept a JSON
response.
See also http://pythonpaste.org/webob/reference.html#accept-headers
>
> But. The problem is complicated a bit by validation, which I would
> like
> to keep the same for web UI and scripting API (I obviously don't
> want to
> duplicate effort like producing separate code for web form value
> validation and another portion of validation code values that come in
> over scripting API).
If your validation code is independent of the response then it can
remain the same, just render validation errors appropriately per
response type.
Cheers,
Chris Miles
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/pylons-discuss?hl=en
-~----------~----~----~----~------~----~------~--~---