Created
August 22, 2018 20:06
-
-
Save xspager/93660ca67f2ef9c47bf59dc8ed1d59d9 to your computer and use it in GitHub Desktop.
Example of how to do a server side authorization and restricted access to Mercadolibre/Mercadolivre API using Flask in a single file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import json | |
import requests as req | |
from flask import Flask, Response, redirect, request | |
app = Flask(__name__) | |
''' | |
Example of how to do a server side authorization and restricted access to Mercadoli[bre|vre] API using Flask in a sigle file. | |
Author: https://github.com/xspager | |
Documentation link: https://developers.mercadolibre.com/en_us/api-docs | |
requirements.txt | |
requests==2.19.1 | |
Flask==1.0.2 | |
python-dotenv==0.9.1 | |
Go to http://applications.mercadolibre.com/ and create a new application, set Redirect URI to "http://localhost" | |
Now create a file .flaskenv with the information about the app: | |
FLASK_APP=<THIS_FILE>.py | |
FLASK_ENV=development | |
APP_ID = <YOUR_APP_ID> | |
SECRET_KEY = <YOUR_SECRET_KEY> | |
To run: | |
flask run | |
TODO: | |
[ ] Document | |
[ ] Store token and refresh tokens | |
[ ] Only try to authenticate if can't make a request and after trying to refresh the token if present | |
''' | |
APP_ID = os.environ.get("APP_ID", default="") | |
SECRET_KEY = os.environ.get("SECRET_KEY", default="") | |
@app.route("/") | |
def index(): | |
''' | |
Start page | |
''' | |
# you will need to change only here to the authorization endpoint for the right country | |
url = "https://auth.mercadolivre.com.br/authorization?response_type=code&client_id={}&redirect_uri=http://localhost:5000/get_token".format( | |
APP_ID | |
) | |
return redirect(url) | |
@app.route("/get_token") | |
def get_token(): | |
''' | |
Other page | |
''' | |
token = request.args.get('code', '') | |
if token is not '': | |
url_template = 'https://api.mercadolibre.com/oauth/token?grant_type=authorization_code&client_id={}&client_secret={}&code={}&redirect_uri=http://localhost:5000/get_token' | |
r = req.post( | |
url_template.format( | |
APP_ID, | |
SECRET_KEY, | |
token | |
), | |
allow_redirects=False | |
) | |
new_token = r.json()['access_token'] | |
url_template = "https://api.mercadolibre.com/users/{user_id}?access_token={token}" | |
url = url_template.format(user_id='me', token=new_token) | |
r = req.get(url) | |
return Response( | |
json.dumps(r.json(), indent=4, sort_keys=True), | |
mimetype='application/json' | |
) | |
return 'No token found' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment