API

This part of the documentation documents all the public classes and functions in Flask-Restless.

class flask.ext.restless.APIManager(app=None, session=None, flask_sqlalchemy_db=None)

Provides a method for creating a public ReSTful JSOn API with respect to a given Flask application object.

The Flask object can be specified in the constructor, or after instantiation time by calling the init_app() method. In any case, the application object must be specified before calling the create_api() method.

init_app(app, session=None, flask_sqlalchemy_db=None)

Stores the specified flask.Flask application object on which API endpoints will be registered and the sqlalchemy.orm.session.Session object in which all database changes will be made.

session is the session.orm.session.Session object in which changes to the database will be made.

flask_sqlalchemy_db is the flask.ext.sqlalchemy.SQLAlchemy object with which app has been registered and which contains the database models for which API endpoints will be created.

If flask_sqlalchemy_db is not None, session will be ignored.

This is for use in the situation in which this class must be instantiated before the Flask application has been created.

To use this method with pure SQLAlchemy, for example:

from flask import Flask
from flask.ext.restless import APIManager
from sqlalchemy import create_engine
from sqlalchemy.orm.session import sessionmaker

apimanager = APIManager()

# later...

engine = create_engine('sqlite:////tmp/mydb.sqlite')
Session = sessionmaker(bind=engine)
mysession = Session()
app = Flask(__name__)
apimanager.init_app(app, session=mysession)

and with models defined with Flask-SQLAlchemy:

from flask import Flask
from flask.ext.restless import APIManager
from flask.ext.sqlalchemy import SQLAlchemy

apimanager = APIManager()

# later...

app = Flask(__name__)
db = SQLALchemy(app)
apimanager.init_app(app, flask_sqlalchemy_db=db)
create_api(*args, **kw)

Creates and registers a ReSTful API blueprint on the flask.Flask application specified in the constructor of this class.

The positional and keyword arguments are passed directly to the create_api_blueprint() method, so see the documentation there.

This is a convenience method for the following code:

blueprint = apimanager.create_api_blueprint(*args, **kw)
app.register_blueprint(blueprint)

Changed in version 0.6: The blueprint creation has been moved to create_api_blueprint(); the registration remains here.

create_api_blueprint(model, methods=frozenset(['GET']), url_prefix='/api', collection_name=None, allow_patch_many=False, allow_functions=False, authentication_required_for=None, authentication_function=None, exclude_columns=None, include_columns=None, validation_exceptions=None, results_per_page=10, max_results_per_page=100, post_form_preprocessor=None, preprocessors=None, postprocessors=None)

Creates an returns a ReSTful API interface as a blueprint, but does not register it on any flask.Flask application.

The endpoints for the API for model will be available at <url_prefix>/<collection_name>. If collection_name is None, the lowercase name of the provided model class will be used instead, as accessed by model.__name__. (If any black magic was performed on model.__name__, this will be reflected in the endpoint URL.)

This function must be called at most once for each model for which you wish to create a ReSTful API. Its behavior (for now) is undefined if called more than once.

This function returns the flask.Blueprint object which handles the endpoints for the model. The returned Blueprint has already been registered with the Flask application object specified in the constructor of this class, so you do not need to register it yourself.

model is the flask.ext.restless.Entity class for which a ReSTful interface will be created. Note this must be a class, not an instance of a class.

methods specify the HTTP methods which will be made available on the ReSTful API for the specified model, subject to the following caveats:

  • If GET is in this list, the API will allow getting a single instance of the model, getting all instances of the model, and searching the model using search parameters.
  • If PATCH is in this list, the API will allow updating a single instance of the model, updating all instances of the model, and updating a subset of all instances of the model specified using search parameters.
  • If DELETE is in this list, the API will allow deletion of a single instance of the model per request.
  • If POST is in this list, the API will allow posting a new instance of the model per request.

The default set of methods provides a read-only interface (that is, only GET requests are allowed).

collection_name is the name of the collection specified by the given model class to be used in the URL for the ReSTful API created. If this is not specified, the lowercase name of the model will be used.

url_prefix the URL prefix at which this API will be accessible.

If allow_patch_many is True, then requests to /api/ will attempt to patch the attributes on each of the instances of the model which match the specified search query. This is False by default. For information on the search query parameter q, see Making search queries.

validation_exceptions is the tuple of possible exceptions raised by validation of your database models. If this is specified, validation errors will be captured and forwarded to the client in JSON format. For more information on how to use validation, see Capturing validation errors.

If allow_functions is True, then requests to /api/eval/ will return the result of evaluating SQL functions specified in the body of the request. For information on the request format, see Function evaluation. This if False by default. Warning: you must not create an API for a model whose name is 'eval' if you set this argument to True.

authentication_required_for is a list of HTTP method names (for example, ['POST', 'PATCH']) for which authentication must be required before clients can successfully make requests. If this keyword argument is specified, authentication_function must also be specified. For more information on requiring authentication, see Requiring authentication for some methods.

authentication_function is a function which accepts no arguments and returns True if and only if a client is authorized to make a request on an endpoint.

If either include_columns or exclude_columns is not None, exactly one of them must be specified. If both are not None, then this function will raise a IllegalArgumentError. exclude_columns must be an iterable of strings specifying the columns of model which will not be present in the JSON representation of the model provided in response to GET requests. Similarly, include_columns specifies the only columns which will be present in the returned dictionary. In other words, exclude_columns is a blacklist and include_columns is a whitelist; you can only use one of them per API endpoint. If either include_columns or exclude_columns contains a string which does not name a column in model, it will be ignored.

If include_columns is an iterable of length zero (like the empty tuple or the empty list), then the returned dictionary will be empty. If include_columns is None, then the returned dictionary will include all columns not excluded by exclude_columns.

See Specifying which columns are provided in responses for information on specifying included or excluded columns on fields of related models.

results_per_page is a positive integer which represents the default number of results which are returned per page. Requests made by clients may override this default by specifying results_per_page as a query argument. max_results_per_page is a positive integer which represents the maximum number of results which are returned per page. This is a “hard” upper bound in the sense that even if a client specifies that greater than max_results_per_page should be returned, only max_results_per_page results will be returned. For more information, see Server-side pagination.

Deprecated since version 0.9.2: The post_form_preprocessor keyword argument is deprecated in version 0.9.2. It will be removed in version 1.0. Replace code that looks like this::

manager.create_api(Person, post_form_preprocessor=foo)

with code that looks like this:

manager.create_api(Person, preprocessors=dict(POST=[foo]))

See Request preprocessors and postprocessors for more information and examples.

post_form_preprocessor is a callback function which takes POST input parameters loaded from JSON and enhances them with other key/value pairs. The example use of this is when your model requires to store user identity and for security reasons the identity is not read from the post parameters (where malicious user can tamper with them) but from the session.

preprocessors is a dictionary mapping strings to lists of functions. Each key is the name of an HTTP method (for example, 'GET' or 'POST'). Each value is a list of functions, each of which will be called before any other code is executed when this API receives the corresponding HTTP request. The functions will be called in the order given here. The postprocessors keyword argument is essentially the same, except the given functions are called after all other code. For more information on preprocessors and postprocessors, see Request preprocessors and postprocessors.

New in version 0.9.2: Added the preprocessors and postprocessors keyword arguments.

New in version 0.9.0: Added the max_results_per_page keyword argument.

New in version 0.7: Added the exclude_columns keyword argument.

New in version 0.6: This functionality was formerly in create_api(), but the blueprint creation and registration have now been separated.

New in version 0.6: Added the results_per_page keyword argument.

New in version 0.5: Added the include_columns and validation_exceptions keyword argument.

New in version 0.4: Added the allow_functions, allow_patch_many, authentication_required_for, authentication_function, and collection_name keyword arguments.

New in version 0.4: Force the model name in the URL to lowercase.

class flask.ext.restless.ProcessingException(message='', status_code=400, *args, **kwargs)

Raised when a preprocessor or postprocessor encounters a problem.

This exception should be raised by functions supplied in the preprocessors and postprocessors keyword arguments to APIManager.create_api. When this exception is raised, all preprocessing or postprocessing halts, so any processors appearing later in the list will not be invoked.

status_code is the HTTP status code of the response supplied to the client in the case that this exception is raised. message is an error message describing the cause of this exception. This message will appear in the JSON object in the body of the response to the client.

Related Topics

This Page