0

I use Python, Flask, Flask-SQLAlchemy and Flask-Restless to create a RESTful API. The database contains a table user. Each user can follow other users and each user can be followed by other users (like in Twitter). So I also have a table followers to link the users (I partially followed Miguel's tutorial). This is my code:

# -*- coding: utf-8 -*-
from flask import Flask

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

# Create the Flask application and the Flask-SQLAlchemy object.
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

followers = db.Table('followers',
    db.Column('follower_id', db.Integer, db.ForeignKey('user.id'), nullable=False),
    db.Column('followed_id', db.Integer, db.ForeignKey('user.id'), nullable=False)
)

# Model declaration
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode, nullable=False)
    # some other properties...
    followed = db.relationship('User', 
        secondary=followers, 
        primaryjoin=(followers.c.follower_id == id), 
        secondaryjoin=(followers.c.followed_id == id), 
        backref=db.backref('followers', lazy='dynamic'), 
        lazy='dynamic')

# Create the database tables.
db.create_all()

# Create the Flask-Restless API manager.
manager = APIManager(app, flask_sqlalchemy_db=db)

# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(User, methods=['GET', 'POST'])

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

To add a new user in the database is easy:

from requests import post

user = {'name':'John Doe'}
post('http://localhost:5000/api/user', json=user)

But what kind of request should I do to add something in the followers table?

1 Answer 1

1

You need to use PATCH.

From this docs:

PATCH /api/person/1

HTTP/1.1 Host: example.com

    { "computers":
      {
        "add": [ {"id": 1} ]
      }
    }

In your case you would do something like:

from requests import patch

follower = {'id':'37'}
cmd = {'followed': { 'add': [ follower ] } }
patch('http://localhost:5000/api/user/1', json=cmd)
Sign up to request clarification or add additional context in comments.

1 Comment

Now I understand, thank you. There was another problem in my code which was disturbing me: in my code, db.relationship(...) was not assigned to anything so the field was not created in the database. Now I assign it to a field followed. I fixed your answer to take this change into account. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.