Peter Gleeson

How to build a JSON API with Python

Create an API that allows client-side interaction with an underlying database.

Add to Pieces

There are a couple of layers between the database and the client — a data abstraction layer and a resource manager layer.

Send JSON-like Response Using Flask

Tags: flask,  python-3.x,  python

Flask is a Python library that provides a ‘micro-framework’ for web development. It is great for rapid development as it comes with a simple-yet-extensible core functionality.

from flask import Flask
app = Flask(__name__)


@app.route('/')
def example():
  return '{"name":"Bob"}'


if __name__ == '__main__':
  app.run()

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Create a New Directory and Navigate Inside

Tags: flask,  shell, directory

Create flask demo directory and change into that directory location.

$ mkdir flask-jsonapi-demo
$ cd flask-jsonapi-demo/

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Creating Virtual Environments for Python Project

Tags: python, shell

Creating virtual environments for each python project is important, and is recommended in this project.

$ python -m venv .venv
$ source .venv/bin/activate

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Install Flask Modules

Tags: shell,  python, rest

Installing modules for flask-rest-jsonapi and sqlalchemy.

$ pip install flask-rest-jsonapi flask-sqlalchemy

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Create Database and Python File

Tags: database, shell, python

Create the python file and the database for the project called artists.db and application.py.

$ touch application.py artists.db

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Create the Database Schema

Tags: python,  sqlalchemy, flask-sqlalchemy, flask, python-3.x

Open application.py in your preferred text editor. Begin by importing some modules. For clarity, modules will be imported as you go. Next, create an object called app as an instance of the Flask class. After that, use SQLAlchemy to connect to the database file you created. The final step is to define and create a table called artists.

return ChessBoard(
   controller: chessBoardController,
   boardOrientation: StreamChat.of(context).currentUser!.id == chessAttachment.whiteUserId ? PlayerColor.white : PlayerColor.black,
);

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Creating an Abstraction Layer

Tags: flask,  python, django

The data abstraction layer is defined as a class which inherits from Marshmallow-JSONAPI’s Schema class. It will provide access via the API to both single records and multiple records from the artists table. Inside this block, the Meta class defines some metadata. Specifically, the name of the URL endpoint for interacting with single records will be artist_one, where each artist will be identified by a URL parameter <id>. The name of the endpoint for interacting with many records will be artist_many.

from marshmallow_jsonapi.flask import Schema
from marshmallow_jsonapi import fields 


# Create data abstraction layer 
class ArtistSchema(Schema):
  class Meta:
    type_ = 'artist'
    self_view = 'artist_one'
    self_view_kwargs = {'id': ''}
    self_view_many = 'artist_many'


  id = fields.Integer()
  name = fields.Str(required=True)
  birth_year = fields.Integer(load_only=True)
  genre = fields.Str()

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Create Resource Managers and Endpoints

Tags: python, ruby, django, ruby-on-rails, activerecord

Create resource managers that inherit from the Flask-Rest-JSONAPI classes called ArtistsMany and ArtistsOne. Then define the api instance and create routes.

# Create resource managers and endpoints
from flask_rest_jsonapi import Api, ResourceDetail, ResourceList 


class ArtistMany(ResourceList):
  schema = ArtistSchema
  data_layer = {'session': db.session, 'model': Artist}


class ArtistOne(ResourceDetail):
  schema = ArtistSchema
  data_layer = {'session': db.session, 'model': Artist}


api = Api(app)
api.route(ArtistMany, 'artist_many', '/artists')
api.route(ArtistOne, 'artist_one', '/artists/')


# main loop to run app in debug mode
if __name__ == '__main__':
  app.run(debug=True)

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Launching the Server via Python Script

Tags: django, markdown, python, python-3.x

Running the the applications.py file and launching the server.

$ python application.py


Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Creating a Table with Additional Imports

Tags: python, python-3.x

Running the the applications.py file and launching the server.

from marshmallow_jsonapi.flask import Relationship
from flask_rest_jsonapi import ResourceRelationship 


# Define the Artwork table
class Artwork(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  title = db.Column(db.String)
  artist_id = db.Column(db.Integer, db.ForeignKey('artist.id'))
  artist = db.relationship('Artist', backref=db.backref('artworks'))

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Creating Data Abstraction Layer

Tags: python

Rewriting the data abstraction layer. This defines an abstraction layer for the artwork table, and adds a relationship between artist and artwork to the ArtistSchema class.

# Create data abstraction
class ArtistSchema(Schema):
  class Meta:
    type_ = 'artist'
    self_view = 'artist_one'
    self_view_kwargs = {'id': ''}
    self_view_many = 'artist_many' id = fields.Integer()
 
  name = fields.Str(required=True)
  birth_year = fields.Integer(load_only=True)
  genre = fields.Str()
  artworks = Relationship(self_view = 'artist_artworks',
    self_view_kwargs = {'id': ''},
    related_view = 'artwork_many',
    many = True,
    schema = 'ArtworkSchema',
    type_ = 'artwork')


class ArtworkSchema(Schema):
  class Meta:
    type_ = 'artwork'
    self_view = 'artwork_one'
    self_view_kwargs = {'id': ''}
    self_view_many = 'artwork_many'
  id = fields.Integer()
  title = fields.Str(required=True)
  artist_id = fields.Integer(required=True)

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Artwork Resource Managers

Tags: python

Next, define new resource managers for accessing artworks many at once and one at a time, and also for accessing the relationships between artist and artwork.

class ArtworkMany(ResourceList):
  schema = ArtworkSchema
  data_layer = {'session': db.session, 'model': Artwork}


class ArtworkOne(ResourceDetail):
  schema = ArtworkSchema 
  data_layer = {'session': db.session, 'model': Artwork}


class ArtistArtwork(ResourceRelationship):
  schema = ArtistSchema
  data_layer = {'session': db.session, 'model': Artist}




Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Add New Endpoints

Tags: route, api, python

Adding new endpoints to the application.py file.

api.route(ArtworkOne, 'artwork_one', '/artworks/')
api.route(ArtworkMany, 'artwork_many', '/artworks')
api.route(ArtistArtwork, 'artist_artworks',
  '/artists//relationships/artworks')

Related links:

  1. https://insomnia.rest/
  2. https://marshmallow-jsonapi.readthedocs.io/en/latest/
  3. https://medium.com/@petergleeson1/how-to-build-a-json-api-with-python-b9ab6f712988
  4. https://www.freecodecamp.org/news/build-a-simple-json-api-in-python/
  5. https://curl.haxx.se/
  6. https://restfulapi.net/http-methods/
  7. https://flask.palletsprojects.com/en/1.1.x/
  8. https://jsonapi.org/
  9. https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/