Skip to content

Commit

Permalink
Some doc fixes for Flask-Restful
Browse files Browse the repository at this point in the history
  • Loading branch information
ueg1990 committed Feb 26, 2015
1 parent 9a62ad7 commit a218e1e
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 40 deletions.
13 changes: 6 additions & 7 deletions docs/extending.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Content Negotiation
-------------------

Out of the box, Flask-RESTful is only configured to support JSON. We made this
decision to give API maintainers full control of over API format support, so a
decision to give API maintainers full control of over API format support; so a
year down the road you don’t have to support people using the CSV
representation of your API you didn’t even know existed. To add additional
mediatypes to your API, you’ll need to declare your supported representations
Expand All @@ -38,7 +38,7 @@ Custom Fields & Inputs
----------------------

One of the most common additions to Flask-RESTful is to define custom types or
fields based on the data your own data types.
fields based on your own data types.

Fields
~~~~~~
Expand Down Expand Up @@ -91,7 +91,7 @@ You can also convert public parameter values to internal representations: ::
return statuses.index(value)


Then you can use these custom input type in your RequestParser: ::
Then you can use these custom input types in your RequestParser: ::

parser = reqparse.RequestParser()
parser.add_argument('OddNumber', type=odd_number)
Expand All @@ -102,7 +102,7 @@ Then you can use these custom input type in your RequestParser: ::
Response Formats
----------------

To support other representations (like xml, csv, html) you can use the
To support other representations (xml, csv, html), you can use the
:meth:`~Api.representation` decorator. You need to have a reference to your API. ::

api = restful.Api(app)
Expand All @@ -116,14 +116,13 @@ These output functions take three parameters, ``data``, ``code``, and
``headers``

``data`` is the object you return from your resource method, code is the HTTP
status code that it expects, and headers are any HTTP headers to set in the
status code that it expects, and headers are any HTTP headers to define in the
response. Your output function should return a Flask response object. ::

def output_json(data, code, headers=None):
"""Makes a Flask response with a JSON encoded body"""
resp = make_response(json.dumps(data), code)
resp.headers.extend(headers or {})

return resp

Another way to accomplish this is to subclass the :class:`~Api` class and
Expand All @@ -142,7 +141,7 @@ provide your own output functions. ::
Resource Method Decorators
--------------------------

There is a property on the :meth:`~flask.ext.restful.Resource` called
There is a property on the :class:`~flask.ext.restful.Resource` class called
method_decorators. You can subclass the Resource and add your own decorators
that will be added to all ``method`` functions in resource. For instance, if
you want to build custom authentication into every request. ::
Expand Down
31 changes: 15 additions & 16 deletions docs/fields.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Output Fields

Flask-RESTful provides an easy way to control what data you actually render in
your response. With the ``fields`` module, you can use whatever objects (ORM
models/custom classes/etc) you want in your resource and ``fields`` lets you
models/custom classes/etc.) you want in your resource; ``fields`` also lets you
format and filter the response so you don't have to worry about exposing
internal data structures.

Expand All @@ -20,8 +20,8 @@ Basic Usage
-----------
You can define a dict or OrderedDict of fields whose keys are names of
attributes or keys on the object to render, and whose values are a class that
will format & return the value for that field. This example has three fields,
two are Strings and one is a DateTime, formatted as RFC 822 date string (ISO 8601
will format & return the value for that field. This example has three fields:
two are Strings and one is a DateTime, formatted as an RFC 822 date string (ISO 8601
is supported as well) ::

from flask.ext.restful import Resource, fields, marshal_with
Expand All @@ -48,15 +48,14 @@ The decorator ``marshal_with`` is what actually takes your data object and appli
field filtering. The marshalling can work on single objects, dicts, or
lists of objects.

Note: marshal_with is a convenience decorator, that is functionally equivalent to the following ``return marshal(db_get_todo(), resource_fields), 200``.
This explicit expression can be used to return other HTTP status codes than 200 along with a successful response (see ``abort`` for errors).
Note: marshal_with is a convenience decorator, that is functionally equivalent to ``return marshal(db_get_todo(), resource_fields), 200``.
This explicit expression can be used to return HTTP status codes other than 200 along with a successful response (see ``abort`` for errors).


Renaming Attributes
-------------------

Often times your public facing field name is different from your internal
attribute naming. To configure this mapping, use the ``attribute`` kwarg. ::
Often times your public facing field name is different from your internal field name. To configure this mapping, use the ``attribute`` keyword argument. ::

fields = {
'name': fields.String(attribute='private_name'),
Expand Down Expand Up @@ -94,8 +93,8 @@ to multiplex a single attribute to multiple output values.


This example assumes that bit 1 in the ``flags`` attribute signifies a
"Normal" or "Urgent" item, and bit 2 signifies "Read" vs "Unread". These
items might be easy to store in a bitfield, but for human readable output it's
"Normal" or "Urgent" item, and bit 2 signifies "Read" or "Unread". These
items might be easy to store in a bitfield, but for a human readable output it's
nice to convert them to seperate string fields. ::

class UrgentItem(fields.Raw):
Expand Down Expand Up @@ -133,7 +132,7 @@ your data object. ::


By default ``fields.Url`` returns a relative uri. To generate an absolute uri that includes
the scheme, hostname and port pass ``absolute=True`` in the field declaration. To override
the scheme, hostname and port, pass the keyword argument ``absolute=True`` in the field declaration. To override
the default scheme, pass the ``scheme`` keyword argument::

fields = {
Expand All @@ -144,7 +143,7 @@ the default scheme, pass the ``scheme`` keyword argument::
Complex Structures
------------------

You can have a flat structure that marshal_with will transform to a nested structure ::
You can have a flat structure that the function ``marshal`` will transform to a nested structure ::

>>> from flask.ext.restful import fields, marshal
>>> import json
Expand All @@ -161,7 +160,7 @@ You can have a flat structure that marshal_with will transform to a nested struc
'{"name": "bob", "address": {"line 1": "123 fake street", "line 2": "", "state": "NY", "zip": "10468", "city": "New York"}}'

Note: the address field doesn't actually exist on the data object, but any of
the sub-fields can access attributes directly of the object as if they were
the sub-fields can access attributes directly from the object as if they were
not nested.

.. _list-field:
Expand Down Expand Up @@ -210,10 +209,10 @@ structures and render them appropriately. ::
'{"billing_address": {"line 1": "123 fake street", "line 2": null, "state": "NY", "zip": "10468", "city": "New York"}, "name": "bob", "shipping_address": {"line 1": "555 nowhere", "line 2": null, "state": "NY", "zip": "10468", "city": "New York"}}'

This example uses two Nested fields. The ``Nested`` constructor takes a dict of
fields to render as sub-fields. The important difference when using ``Nested``
vs nested dicts as the previous example is the context for attributes. In
this example "billing_address" is a complex object that has it's own fields,
the contexted passed to the nested field is the sub-object instead of the
fields to render as sub-fields. The important difference between the ``Nested`` constructor
and nested dicts (previous example), is the context for attributes. In
this example, "billing_address" is a complex object that has its own fields;
the context passed to the nested field is the sub-object instead of the
original "data" object. In other words: ``data.billing_address.addr1`` is in
scope here, whereas in the previous example ``data.addr1`` was the location
attribute. Remember: Nested and List objects create a new scope for attributes.
21 changes: 10 additions & 11 deletions docs/intermediate-usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ There are many different ways to organize your Flask-RESTful app, but here
we'll describe one that scales pretty well with larger apps and maintains
a nice level organization.

The basic idea is to split your app into three main parts. The routes, the
The basic idea is to split your app into three main parts: the routes, the
resources, and any common infrastructure.

Here's an example directory structure: ::
Expand Down Expand Up @@ -132,12 +132,11 @@ exercise a larger amount of options. We'll define a resource named "User". ::

@marshal_with(user_fields)
def get(self, id):
args = get_parser.parse_args()
args = post_parser.parse_args()
user = fetch_user(id)
return user

As you can see, we create a `post_parser` specifically to handle parsing
the arguments provided on POST. Let's step through the definition of each
As you can see, we create a `post_parser` specifically to handle the parsing of arguments provided on POST. Let's step through the definition of each
argument. ::

post_parser.add_argument(
Expand Down Expand Up @@ -171,11 +170,11 @@ email type was invalid. ::

The `user_priority` type takes advantage of the `choices` argument. This
means that if the provided `user_priority` value doesn't fall in the range
specified by the `choices` argument (in this case [1, 2, 3, 4]) Flask-RESTful
specified by the `choices` argument (in this case [1, 2, 3, 4]), Flask-RESTful
will automatically respond with a 400 and a descriptive error message.

That covers the inputs. We also defined some interesting field types in the
`user_fields` dictionary to show showcase a couple of the more exotic types. ::
`user_fields` dictionary to showcase a couple of the more exotic types. ::

user_fields = {
'id': fields.Integer,
Expand All @@ -202,8 +201,8 @@ value returned from the `username` field.
Next up, check out `fields.Nested`. ::

'links': fields.Nested({
'friends': fields.Url('/Users/{id}/Friends', absolute=True),
'posts': fields.Url('Users/{id}/Posts', absolute=True),
'friends': fields.Url('/users/{id}/Friends', absolute=True),
'posts': fields.Url('/users/{id}/Posts', absolute=True),
}),

This field is used to create a sub-object in the response. In this case,
Expand All @@ -213,9 +212,9 @@ way that it would be an acceptable argument to `marshal` by itself.

Finally, we used the `fields.Url` field type. ::

'friends': fields.Url('/Users/{id}/Friends', absolute=True),
'posts': fields.Url('Users/{id}/Posts', absolute=True),
'friends': fields.Url('/users/{id}/Friends', absolute=True),
'posts': fields.Url('/users/{id}/Posts', absolute=True),

It takes a string that can be formatted in the same manner as `fields.FormattedString`
which we covered above. Passing `absolute=True` ensures that the generated Urls
which we covered above. Passing `absolute=True` ensures that the generated urls
will have the hostname included.
5 changes: 3 additions & 2 deletions docs/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ never be used in a production environment. ::

$ python api.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader


Now open up a new prompt to test out your API using curl ::
Expand Down Expand Up @@ -241,7 +242,7 @@ Save this example in api.py ::


# Todo
# show a single todo item and lets you delete them
# shows a single todo item and lets you delete a todo item
class Todo(Resource):
def get(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
Expand All @@ -260,7 +261,7 @@ Save this example in api.py ::


# TodoList
# shows a list of all todos, and lets you POST to add new tasks
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS
Expand Down
6 changes: 3 additions & 3 deletions docs/reqparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ Request Parsing

.. currentmodule:: flask.ext.restful

Flask-RESTful's request parsing interface is modeled after the ``argparse``
Flask-RESTful's request parsing interface, :py:class:`reqparse`, is modeled after the ``argparse``
interface. It's designed to provide simple and uniform access to any
variable on the :py:class:`flask.request` object in Flask.

Basic Arguments
---------------

Here's a simple example of the request parser. It looks for two arguments in
the :py:attr:`flask.Request.values` dict. One of type ``int``, and the other of
the :py:attr:`flask.Request.values` dict: one of type ``int``, and the other of
type ``str`` ::

from flask.ext.restful import reqparse
Expand Down Expand Up @@ -64,7 +64,7 @@ Other Destinations
------------------

If for some reason you'd like your argument stored under a different name once
it's parsed, you can use the ``dest`` kwarg. ::
it's parsed, you can use the ``dest`` keyword argument. ::

parser.add_argument('name', type=str, dest='public_name')

Expand Down
2 changes: 1 addition & 1 deletion docs/testing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Example::
$ source env/bin/activate
$ nosetests tests/test_reqparse.py:ReqParseTestCase.test_parse_choices_insensitive

Alternately, push changes to your fork on Github, and Travis will run the tests
Alternately, if you push changes to your fork on Github, Travis will run the tests
for your branch automatically.

A Tox config file is also provided so you can test against multiple python
Expand Down

0 comments on commit a218e1e

Please sign in to comment.