Reputation: 3095
I'm working on a Flask example that takes blog posts and adding them to a database through a RESTful service.
Prior to implementing the RESTful service, I was adding blog posts to a local database by doing the following:
@main.route('/', methods=['GET', 'POST'])
def index():
form = PostForm()
if current_user.can(Permission.WRITE_ARTICLES) and \
form.validate_on_submit():
post = Post(body=form.body.data,
author=current_user._get_current_object())
db.session.add(post)
return redirect(url_for('.index'))
Now that I've gotten to the RESTful service section, the following to_json()
and from_json()
functions have been to the Post model:
//Convert a post from JSON
//Class Post(db.Model)
def to_json(self):
json_post = {
'url': url_for('api.get_post', id=self.id, _external=True),
'body': self.body,
'body_html': self.body_html,
'timestamp': self.timestamp,
'author': url_for('api.get_user', id=self.author_id,
_external=True),
'comments': url_for('api_get_post_comments', id=self.id,
_external=True),
'comment_count': self.comments.count()
}
return json_post
//Create a blog post from JSON
//Class Post(db.Model)
@staticmethod
def from_json(json_post):
body = json_post.get('body')
if body is None or body == '':
raise ValidationError('post does not have a body')
return Post(body=body)
The following inserts a new blog post in the database:
//POST resource handler for posts
@api.route('/posts/', methods=['POST'])
@permission_required(Permission.WRITE_ARTICLES)
def new_post():
post = Post.from_json(request.json)
post.author = g.current_user
db.session.add(post)
db.session.commit()
return jsonify(post.to_json()), 201, \
{'Location': url_for('api.get_post', id=post.id, _external=True)}
Would really appreciate it if someone could explain how these functions work with each other. My understanding of it all is that a blog post is typed up on a client device and in order to send it to the web service, the to_json
function is called to convert the post to JSON. Once the web service receives the JSON version of the blog post, the from_json
function is called to convert the JSON post back to its original state. Is that correct?
Edit:
Just re-read the page and I think my understanding was reverse of whats actually happening. In order to get a blog post from the web service, the to_json
function is called to convert the data to JSON. Then on the client side, the from_json
function is called to convert the data back from JSON.
Upvotes: 1
Views: 521
Reputation: 1651
Your edit is correct. A common response format for a REST API is JSON, which is why the the response is converted "to JSON" when returning.
Also a common header for sending data to a REST API is application/json
, which is why the code converts the received data "from JSON".
Upvotes: 1