Marshmallow Python

broken image


  1. Marshmallow Snake
  2. Marshmallow Python
  3. Marshmallow Python Pypi
  4. Marshmallow Python Schema
  5. Flask Marshmallow

Marshmallow is a library converting different datatypes to Python objects. The most common usage of Marshmallow is to deserialize JSON object to Python object or serialize Python object to JSON object to be used in web API. Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy. A lightweight library for converting complex objects to and from simple Python datatypes. A friendly library for parsing HTTP request arguments, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, Pyramid, webapp2, Falcon, and aiohttp. Marshmallow alternatives and similar packages ultrajson. A fast JSON decoder and encoder written in C with Python bindings. Get performance insights in less than 4 minutes. Scout APM uses tracing logic that ties bottlenecks to source code. A Python bindings for simdjson. Marshmallow requires Python = 3.5. It has no external dependencies. If you find marshmallow useful, please consider supporting the team with a donation.

changelog //github //pypi //issues

Flask + marshmallow for beautiful APIs¶

Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.

Get it now¶

Create your app.

Write your models.

Define your output format with marshmallow.

Output the data in your views.

Optional Flask-SQLAlchemy Integration¶

Flask-Marshmallow includes useful extras for integrating with Flask-SQLAlchemy and marshmallow-sqlalchemy.

To enable SQLAlchemy integration, make sure that both Flask-SQLAlchemy and marshmallow-sqlalchemy are installed.

Next, initialize the SQLAlchemy and Marshmallow extensions, in that order.

Note on initialization order

Flask-SQLAlchemy must be initialized before Flask-Marshmallow. Pip3.

Declare your models like normal.

Generate marshmallow Schemas from your models using SQLAlchemySchema or SQLAlchemyAutoSchema.

You can now use your schema to dump and load your ORM objects.

SQLAlchemySchema is nearly identical in API to marshmallow_sqlalchemy.SQLAlchemySchema with the following exceptions:

  • By default, SQLAlchemySchema uses the scoped session created by Flask-SQLAlchemy.

  • SQLAlchemySchema subclasses flask_marshmallow.Schema, so it includes the jsonify method.

Note: By default, Flask's jsonify method sorts the list of keys and returns consistent results to ensure that external HTTP caches aren't trashed. As a side effect, this will override ordered=Truein the SQLAlchemySchema's classMeta (if you set it). To disable this, set JSON_SORT_KEYS=False in your Flask app config. In production it's recommended to let jsonify sort the keys and not set ordered=True in your SQLAlchemySchema in order to minimize generation time and maximize cacheability of the results.

You can also use ma.HyperlinkRelated fields if you want relationships to be represented by hyperlinks rather than primary keys.

Marshmallow Snake

The first argument to the HyperlinkRelated constructor is the name of the view used to generate the URL, just as you would pass it to the url_for function. If your models and views use the id attributeas a primary key, you're done; otherwise, you must specify the name of theattribute used as the primary key.

To represent a one-to-many relationship, wrap the HyperlinkRelated instance in a marshmallow.fields.List field, like this:

API¶

flask_marshmallow¶

Integrates the marshmallow serialization/deserialization librarywith your Flask application.

classflask_marshmallow.Marshmallow(app=None)

Wrapper class that integrates Marshmallow with a Flask application.

To use it, instantiate with an application:

The object provides access to the Schema class,all fields in marshmallow.fields, as well as the Flask-specificfields in flask_marshmallow.fields.

You can declare schema like so:

In order to integrate with Flask-SQLAlchemy, this extension must be initialized afterflask_sqlalchemy.SQLAlchemy.

This gives you access to ma.SQLAlchemySchema and ma.SQLAlchemyAutoSchema, which generatemarshmallow Schema classes based on the passed in model or table.

Parameters

app (Flask) – The Flask application object.

init_app(app)

Initializes the application with the extension.

Parameters

app (Flask) – The Flask application object.

classflask_marshmallow.Schema(*, only:Optional[Union[Sequence[str],Set[str]]]=None, exclude:Union[Sequence[str],Set[str]]=(), many:bool=False, context:Optional[Dict]=None, load_only:Union[Sequence[str],Set[str]]=(), dump_only:Union[Sequence[str],Set[str]]=(), partial:Union[bool,Sequence[str],Set[str]]=False, unknown:Optional[str]=None)

Base serializer with which to define custom serializers.

See marshmallow.Schema for more details about the Schema API.

jsonify(obj, many=object>, *args, **kwargs)

Return a JSON response containing the serialized data.

Marshmallow Python

Parameters
  • obj – Object to serialize.

  • many (bool) – Whether obj should be serialized as an instanceor as a collection. If unset, defaults to the value of themany attribute on this Schema.

  • kwargs – Additional keyword arguments passed to flask.jsonify.

Changed in version 0.6.0: Takes the same arguments as marshmallow.Schema.dump. Additionalkeyword arguments are passed to flask.jsonify.

Changed in version 0.6.3: The many argument for this method defaults to the value ofthe many attribute on the Schema. Previously, the manyargument of this method defaulted to False, regardless of thevalue of Schema.many.

flask_marshmallow.pprint(obj, *args, **kwargs)None

Pretty-printing function that can pretty-print OrderedDictslike regular dictionaries. Useful for printing the output ofmarshmallow.Schema.dump().

Deprecated since version 3.7.0: marshmallow.pprint will be removed in marshmallow 4.

flask_marshmallow.fields¶

Custom, Flask-specific fields.

See the marshmallow.fields module for the list of all fields available from themarshmallow library.

classflask_marshmallow.fields.AbsoluteURLFor(endpoint, values=None, **kwargs)

Field that outputs the absolute URL for an endpoint.

flask_marshmallow.fields.AbsoluteUrlFor

alias of flask_marshmallow.fields.AbsoluteURLFor

classflask_marshmallow.fields.Hyperlinks(schema, **kwargs)

Field that outputs a dictionary of hyperlinks,given a dictionary schema with URLForobjects as values.

Example:

URLFor objects can be nested within the dictionary.

Parameters

schema (dict) – A dict that maps names toURLFor fields.

classflask_marshmallow.fields.URLFor(endpoint, values=None, **kwargs)

Field that outputs the URL for an endpoint. Acts identically toFlask's url_for function, except that arguments can be pulled from theobject to be serialized, and **values should be passed to the valuesparameter.

Usage:

Parameters
  • endpoint (str) – Flask endpoint name.

  • values (dict) – Same keyword arguments as Flask's url_for, except stringarguments enclosed in <> will be interpreted as attributes to pullfrom the object.

  • kwargs – keyword arguments to pass to marshmallow field (e.g. required).

flask_marshmallow.fields.UrlFor

alias of flask_marshmallow.fields.URLFor

Python

flask_marshmallow.sqla¶

Integration with Flask-SQLAlchemy and marshmallow-sqlalchemy. ProvidesSQLAlchemySchema andSQLAlchemyAutoSchema classesthat use the scoped session from Flask-SQLAlchemy.

classflask_marshmallow.sqla.DummySession

Placeholder session object.

classflask_marshmallow.sqla.HyperlinkRelated(endpoint, url_key='id', external=False, **kwargs)

Marshmallow Python Pypi

Field that generates hyperlinks to indicate references between models,rather than primary keys.

Parameters
  • endpoint (str) – Flask endpoint name for generated hyperlink.

  • url_key (str) – The attribute containing the reference's primarykey. Defaults to 'id'.

  • external (bool) – Set to True if absolute URLs should be used,instead of relative URLs.

classflask_marshmallow.sqla.SQLAlchemyAutoSchema(*args, **kwargs)

SQLAlchemyAutoSchema that automatically generates marshmallow fieldsfrom a SQLAlchemy model's or table's column.Uses the scoped session from Flask-SQLAlchemy by default.

See marshmallow_sqlalchemy.SQLAlchemyAutoSchema for more detailson the SQLAlchemyAutoSchema API. Chime account create.

OPTIONS_CLASS

alias of flask_marshmallow.sqla.SQLAlchemyAutoSchemaOpts

classflask_marshmallow.sqla.SQLAlchemyAutoSchemaOpts(meta, **kwargs)
classflask_marshmallow.sqla.SQLAlchemySchema(*args, **kwargs)

SQLAlchemySchema that associates a schema with a model via themodel class Meta option, which should be adb.Model class from flask_sqlalchemy. Uses thescoped session from Flask-SQLAlchemy by default.

See marshmallow_sqlalchemy.SQLAlchemySchema for more detailson the SQLAlchemySchema API.

OPTIONS_CLASS

alias of flask_marshmallow.sqla.SQLAlchemySchemaOpts

classflask_marshmallow.sqla.SQLAlchemySchemaOpts(meta, **kwargs)

Project Info¶

In previous article we have seen normal Rest API with python and Flask which stores information into list and retrive data from list. So in this article we are going to build REST API with flask and SQLAlchemy and Marshmallow libraries with Sqlite database.

First of all Let's learn something about SQLAlchemy and marshmallow

SQLAlchemy :

SQLAlchemy is python SQL toolkit and ORM (Object relational mapping) that gives developer the full power and flexibility of SQL. Where flask-sqlalchemy is flask extension that adds support for SQLAlchemy to flask application.

Reference : https://www.sqlalchemy.org/ , https://flask-sqlalchemy.palletsprojects.com/en/2.x/

Marshmallow :

Marshmallow is an ORM/ODM/framework-agnostic library for converting complex data types, such as objects, to and from native Python data types.

Marshmallow schemas can be used to:

  • Validate input data.
  • De-serialize input data to app-level objects.
  • Serialize app-level objects to primitive Python types. The serialized objects can then be rendered to standard formats such as JSON for use in an HTTP API.

Flask-Marshmallow :

Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.

First of all we need to set virtual environment for your flask api project.

Once all setup is done , create one python file app.py and we are going to learn step by step process to write API in flask.

First, we will write all required import statements

Second, We are initializing our flask app and setting db location for SQLAlchemy and generate object for SQLAlchemy and marshmallow

After that we are going to make one Model class for User which has id , username and email as their columns and below we have defined structure of response of our endpoint. We have defined user_schema as instance of UserSchema and Users_schema as instance of UserSchema with multiple fields.

Now we are ready to set routes for our endpoint so let's first make our first end point which has route to '/user' and HTTP method as POST, which can we used for adding new Users into our database.

Another end point which has Route '/user' but with GET as HTTP method, which can be used as getting users list.

In this part we are going to define route as '/user/' with HTTP method as GET , which can be used to get particular users details by passing Id as an argument.

Below is code snippet for updating users information by passing id in route '/user/' with PUT as HTTP method.

Lastly, We have route which can be used for DELETE user from database with Id passed in end point and HTTP method DELETE

That's it. We have added all required code for adding , updating , deleting and selecting users from database. Now let's make entry point for this code

So, Once we have our code is ready , first of all we need to initialize database by running below code

Marshmallow Python Schema

Great, So we are all set to run our application, Let's run server by running below command in your terminal.

Flask Marshmallow

So this will start flask server with port 5000 and it can be accessible with http://127.0.0.1:5000/users and we can now use POSTMAN for running API with POST , GET , PUT and DELETE functions.

Complete code for this tutorial can be found below





broken image