API¶
This part of the documentation documents all the public classes and functions in Flask-Restless-NG.
The API Manager class¶
- class flask_restless.APIManager(app=None, session=None, preprocessors=None, postprocessors=None, url_prefix='/api', include_links: bool = False)¶
Provides a method for creating a public ReSTful JSON API with respect to a given
Flask
application object.The
Flask
object can either be specified in the constructor, or after instantiation time by calling theinit_app()
method.app is the
Flask
object containing the user’s Flask application.session is the
Session
object in which changes to the database will be made.For example, to use this class with models defined in pure SQLAlchemy:
from flask import Flask from flask.ext.restless import APIManager from sqlalchemy import create_engine from sqlalchemy.orm.session import sessionmaker engine = create_engine('sqlite:////tmp/mydb.sqlite') Session = sessionmaker(bind=engine) my_session = Session() app = Flask(__name__) api_manager = APIManager(app, session=my_session)
url_prefix is the URL prefix at which each API created by this instance will be accessible. For example, if this is set to
'foo'
, then this method creates endpoints of the form/foo/<collection_name>
whencreate_api()
is called. If the url_prefix is set in thecreate_api()
, the URL prefix set in the constructor will be ignored for that endpoint.postprocessors and preprocessors must be dictionaries as described in the section Request preprocessors and postprocessors. These preprocessors and postprocessors will be applied to all requests to and responses from APIs created using this APIManager object. The preprocessors and postprocessors given in these keyword arguments will be prepended to the list of processors given for each individual model when using the
create_api_blueprint()
method (more specifically, the functions listed here will be executed before any functions specified in thecreate_api_blueprint()
method). For more information on using preprocessors and postprocessors, see Request preprocessors and postprocessors.include_links controls whether to include link objects in resource objects https://jsonapi.org/format/#document-links
- init_app(app)¶
Registers any created APIs on the given Flask application.
This function should only be called if no Flask application was provided in the app keyword argument to the constructor of this class.
When this function is invoked, any blueprint created by a previous invocation of
create_api()
will be registered on app by calling theregister_blueprint()
method.To use this method with pure SQLAlchemy, for example:
from flask import Flask from flask_restless import APIManager from sqlalchemy import create_engine from sqlalchemy.orm.session import sessionmaker engine = create_engine('sqlite:////tmp/mydb.sqlite') Session = sessionmaker(bind=engine) mysession = Session() # Here create model classes, for example User, Comment, etc. ... # Create the API manager and create the APIs. api_manager = APIManager(session=mysession) api_manager.create_api(User) api_manager.create_api(Comment) # Later, call `init_app` to register the blueprints for the # APIs created earlier. app = Flask(__name__) api_manager.init_app(app)
and with models defined with Flask-SQLAlchemy:
from flask import Flask from flask_restless import APIManager from flask_sqlalchemy import SQLAlchemy db = SQLALchemy(app) # Here create model classes, for example User, Comment, etc. ... # Create the API manager and create the APIs. api_manager = APIManager(session=db.session) api_manager.create_api(User) api_manager.create_api(Comment) # Later, call `init_app` to register the blueprints for the # APIs created earlier. app = Flask(__name__) api_manager.init_app(app)
- create_api(*args, **kw)¶
Creates and possibly registers a ReSTful API blueprint for the given SQLAlchemy model.
If a Flask application was provided in the constructor of this class, the created blueprint is immediately registered on that application. Otherwise, the blueprint is stored for later registration when the
init_app()
method is invoked. In that case, the blueprint will be registered each time theinit_app()
method is invoked.The keyword arguments for this method are exactly the same as those for
create_api_blueprint()
, and are passed directly to that method. However, unlike that method, this method accepts only a single positional argument, model, the SQLAlchemy model for which to create the API. A UUID will be automatically generated for the blueprint name.For example, if you only wish to create APIs on a single Flask application:
app = Flask(__name__) session = ... # create the SQLAlchemy session manager = APIManager(app=app, session=session) manager.create_api(User)
If you want to create APIs before having access to a Flask application, you can call this method before calling
init_app()
:session = ... # create the SQLAlchemy session manager = APIManager(session=session) manager.create_api(User) # later... app = Flask(__name__) manager.init_app(app)
If you want to create an API and register it on multiple Flask applications, you can call this method once and
init_app()
multiple times with different app arguments:session = ... # create the SQLAlchemy session manager = APIManager(session=session) manager.create_api(User) # later... app1 = Flask('application1') app2 = Flask('application2') manager.init_app(app1) manager.init_app(app2)
- create_api_blueprint(name: str, model, methods=frozenset({'GET'}), url_prefix: Optional[str] = None, collection_name: Optional[str] = None, only=None, exclude=None, additional_attributes=None, validation_exceptions=None, page_size: int = 10, max_page_size: int = 100, preprocessors=None, postprocessors=None, primary_key: Optional[str] = None, serializer: Optional[Serializer] = None, deserializer: Optional[Deserializer] = None, includes=None, allow_to_many_replacement: bool = False, allow_delete_from_to_many_relationships: bool = False, allow_client_generated_ids: bool = False, allow_functions: bool = False)¶
Creates and 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 isNone
, the lowercase name of the provided model class will be used instead, as accessed bymodel.__table__.name
. (If any black magic was performed onmodel.__table__
, this will be reflected in the endpoint URL.) For more information, see Collection name.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 that handles the endpoints for the model. The returnedBlueprint
has not been registered with theFlask
application object specified in the constructor of this class, so you will need to register it yourself to make it available on the application. If you don’t need access to theBlueprint
object, usecreate_api_blueprint()
instead, which handles registration automatically.name is the name of the blueprint that will be created.
model is the SQLAlchemy model class for which a ReSTful interface will be created.
app is the
Flask
object on which we expect the blueprint created in this method to be eventually registered. If not specified, the Flask application specified in the constructor of this class is used.methods is a list of strings specifying the HTTP methods that will be made available on the ReSTful API for the specified model.
If
'GET'
is in the list, GET requests will be allowed at endpoints for collections of resources, resources, to-many and to-one relations of resources, and particular members of a to-many relation. Furthermore, relationship information will be accessible. For more information, see Fetching resources and relationships.If
'POST'
is in the list, POST requests will be allowed at endpoints for collections of resources. For more information, see Creating resources.If
'DELETE'
is in the list, DELETE requests will be allowed at endpoints for individual resources. For more information, see Deleting resources.If
'PATCH'
is in the list, PATCH requests will be allowed at endpoints for individual resources. Replacing a to-many relationship when issuing a request to update a resource can be enabled by settingallow_to_many_replacement
toTrue
.Furthermore, to-one relationships can be updated at the relationship endpoints under an individual resource via PATCH requests. This also allows you to add to a to-many relationship via the POST method, delete from a to-many relationship via the DELETE method (if
allow_delete_from_to_many_relationships
is set toTrue
), and replace a to-many relationship via the PATCH method (ifallow_to_many_replacement
is set toTrue
). For more information, see Updating resources and Updating relationships.
The default set of methods provides a read-only interface (that is, only GET requests are allowed).
url_prefix is the URL prefix at which this API will be accessible. For example, if this is set to
'/foo'
, then this method creates endpoints of the form/foo/<collection_name>
. If not set, the default URL prefix specified in the constructor of this class will be used. If that was not set either, the default'/api'
will be used.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. For example, if this is set to
'foo'
, then this method creates endpoints of the form/api/foo
,/api/foo/<id>
, etc.If only is not
None
, it must be a list of columns and/or relationships of the specified model, given either as strings or as the attributes themselves. If it is a list, only these fields will appear in the resource object representation of an instance of model. In other words, only is a allowlist of fields. Theid
andtype
elements of the resource object will always be present regardless of the value of this argument. If only contains a string that does not name a column in model, it will be ignored.If additional_attributes is a list of strings, these attributes of the model will appear in the JSON representation of an instance of the model. This is useful if your model has an attribute that is not a SQLAlchemy column but you want it to be exposed. If any of the attributes does not exist on the model, a
AttributeError
is raised.If exclude is not
None
, it must be a list of columns and/or relationships of the specified model, given either as strings or as the attributes themselves. If it is a list, all fields except these will appear in the resource object representation of an instance of model. In other words, exclude is an blocklist of fields. Theid
andtype
elements of the resource object will always be present regardless of the value of this argument. If exclude contains a string that does not name a column in model, it will be ignored.If either only or exclude is not
None
, exactly one of them must be specified; if both are notNone
, then this function will raise aIllegalArgumentError
.See Specifying which fields appear in responses for more information on specifying which fields will be included in the resource object representation.
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 the format described by the JSON API specification. For more information on how to use validation, see Capturing validation errors.
page_size must be a positive integer that represents the default page size for responses that consist of a collection of resources. Requests made by clients may override this default by specifying
page_size
as a query parameter. max_page_size must be a positive integer that represents the maximum page size that a client can request. Even if a client specifies that greater than max_page_size should be returned, at most max_page_size results will be returned. For more information, see Pagination.serializer and deserializer are custom serialization classes. See Custom serialization.
preprocessors is a dictionary mapping strings to lists of functions. Each key represents a type of endpoint (for example,
'GET_RESOURCE'
or'GET_COLLECTION'
). 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.primary_key is a string specifying the name of the column of model to use as the primary key for the purposes of creating URLs. If the model has exactly one primary key, there is no need to provide a value for this. If model has two or more primary keys, you must specify which one to use. For more information, see Specifying one of many primary keys.
includes must be a list of strings specifying which related resources will be included in a compound document by default when fetching a resource object representation of an instance of model. Each element of includes is the name of a field of model (that is, either an attribute or a relationship). For more information, see Inclusion of related resources.
If allow_to_many_replacement is
True
and this API allows PATCH requests, the server will allow two types of requests. First, it allows the client to replace the entire collection of resources in a to-many relationship when updating an individual instance of the model. Second, it allows the client to replace the entire to-many relationship when making a PATCH request to a to-many relationship endpoint. This isFalse
by default. For more information, see Updating resources and Updating relationships.If allow_delete_from_to_many_relationships is
True
and this API allows PATCH requests, the server will allow the client to delete resources from any to-many relationship of the model. This isFalse
by default. For more information, see Updating relationships.If allow_client_generated_ids is
True
and this API allows POST requests, the server will allow the client to specify the ID for the resource to create. JSON API recommends that this be a UUID. This isFalse
by default. For more information, see Creating resources.If allow_functions is
True
, then GET requests to/api/eval/<collection_name>
will return the result of evaluating SQL functions specified in the body of the request. For information on the request format, see functionevaluation. This isFalse
by default.Warning
This is deprecated and going to be removed in the next major version
Warning
If
allow_functions
isTrue
, you must not create an API for a model whose name is'eval'
.
Serialization helpers¶
- class flask_restless.Serializer¶
An object that, when called, returns a dictionary representation of a given instance of a SQLAlchemy model.
- class flask_restless.Deserializer(session, model, api_manager)¶
An object that, when called, returns an instance of the SQLAlchemy model specified at instantiation time.
session is the SQLAlchemy session in which to look for any related resources.
model is the class of which instances will be created by the
__call__()
method.This is a base class with no implementation.
- class flask_restless.SerializationException(instance, message=None, resource=None, resource_type=None, resource_id=None, *args, **kw)¶
Raised when there is a problem serializing an instance of a SQLAlchemy model to a dictionary representation.
instance is the (problematic) instance on which
Serializer.__call__()
was invoked.message is an optional string describing the problem in more detail.
resource is an optional partially-constructed serialized representation of
instance
.Each of these keyword arguments is stored in a corresponding instance attribute so client code can access them.
- class flask_restless.DeserializationException(*args, **kw)¶
Raised when there is a problem deserializing a Python dictionary to an instance of a SQLAlchemy model.
Subclasses that wish to provide more detailed about the problem should set the
detail
attribute to be a string, either as a class-level attribute or as an instance attribute.
Pre- and postprocessor helpers¶
- class flask_restless.ProcessingException(id_=None, links=None, status=400, code=None, title=None, detail=None, source=None, meta=None, *args, **kw)¶
Raised when a preprocessor or postprocessor encounters a problem.
This exception should be raised by functions supplied in the
preprocessors
andpostprocessors
keyword arguments toAPIManager.create_api
. When this exception is raised, all preprocessing or postprocessing halts, so any processors appearing later in the list will not be invoked.The keyword arguments
id_
,href
status
,code
,title
,detail
,links
,paths
correspond to the elements of the JSON API error object; the values of these keyword arguments will appear in the error object returned to the client.Any additional positional or keyword arguments are supplied directly to the superclass,
werkzeug.exceptions.HTTPException
.