avatar

Did someone asked for a Rest API ?


13-02-2015 10:28 by depado

Rest API and Curl


Jokingly, a friend of mine asked if he could post some articles within his terminal. Now this joke is no more a joke, even if it looks a bit more complicated. There is now a single url that allows basic Http Auth and only accept the POST method. markdownblog.com/curl/post

Here is how you can post a new article :

curl -u $username -i -X POST -H "Content-Type: application/json" -d '{"title":Title","content":Content"}' http://markdownblog.com/curl/post

Of course you'll have to enter your password. The title isn't parsed as markdown, but the content is. Just like when you write a regular article.

# -*- coding: utf-8 -*-

from datetime import datetime

from flask import g, jsonify, request
from flask_httpauth import HTTPBasicAuth

from app import app, db
from app.models import User, Post

auth = HTTPBasicAuth()

@auth.verify_password
def verify_password(username, password):
    user = db.session.query(User).filter_by(username=username).first()
    if not user or not user.check_password(password):
        return False
    g.user = user
    return True


@app.route('/curl/post', methods=['POST'])
@auth.login_required
def curl_post():
    try:
        content = request.json.get('content')
        title = request.json.get('title')
        post = Post(user=g.user, title=title, content=content, pub_date=datetime.now())
        post.save()
        return jsonify({'data': 'Posted Successfully.'})
    except:
        return jsonify({'data': 'Something Went Wrong.'})