[GH-ISSUE #535] Unable to load user data on AWS Lambda #324

Closed
opened 2026-02-27 23:22:00 +03:00 by kerem · 1 comment
Owner

Originally created by @alexcaulfield on GitHub (Jul 8, 2020).
Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/535

Describe the bug
I'm currently trying to deploy my Flask app using the Serverless framework and AWS Lambda. When the user logs in and is redirected to a frontend page that queries for user data using the returned code URL param, the API fails but does not return an error.

Your code

IS_OFFLINE = os.environ.get('IS_OFFLINE')

# Setting secret keys based on environment
SPOTIFY_CLIENT_ID     = config('SPOTIFY_CLIENT_ID')     if IS_OFFLINE else os.environ['SPOTIFY_CLIENT_ID']
SPOTIFY_CLIENT_SECRET = config('SPOTIFY_CLIENT_SECRET') if IS_OFFLINE else os.environ['SPOTIFY_CLIENT_SECRET']
APP_SECRET_KEY        = config('APP_SECRET_KEY')        if IS_OFFLINE else os.environ['APP_SECRET_KEY']

# Setting URLs based on environment
SETLISTIFY_CLIENT_BASE = 'http://localhost:3000' if IS_OFFLINE else PROD_URL
REDIRECT_URI           = f"{SETLISTIFY_CLIENT_BASE}/callback"

SPOTIFY_API_BASE = 'https://accounts.spotify.com'

SCOPE = 'playlist-modify-public'
CACHE = '.spotipyoauthcache'

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = APP_SECRET_KEY
app.config['SESSION_TYPE'] = 'filesystem'
Session(app)
CORS(app, supports_credentials=True)
auth_manager = spotipy.oauth2.SpotifyOAuth(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, REDIRECT_URI, scope=SCOPE, cache_path=CACHE)
spotify = spotipy.Spotify(auth_manager=auth_manager)

@app.route("/authUrl")
def verify():
    authUrl = auth_manager.get_authorize_url()
    return jsonify({'authUrl': authUrl})

@app.route("/getUser", methods=['POST'])
def get_user():
    session.clear()
    code = request.json.get('code')

    session['token_info'] = auth_manager.get_access_token(code)
    results = spotify.current_user()

    return jsonify(results)

Frontend query

      const body = JSON.stringify({
        'code': params.code
      });
      fetch(`${fetchUrl()}/getUser`, {
        method: 'post',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: body
      }).then(res => res.json())
        .then(data => {
          setUser(data);
          handleLogin();
        });

Expected behavior
User data is returned via this request

Output
No errors are displayed in CloudWatch or in Serverless

Environment:

  • OS: [Mac]
  • Python version [3.7.0]
  • spotipy version [2.13.0]
  • your IDE (if using any) [WebStorm]

Additional context
https://www.serverless.com/blog/flask-python-rest-api-serverless-lambda-dynamodb/
Used this to get started up with Flask/Lambda

Originally created by @alexcaulfield on GitHub (Jul 8, 2020). Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/535 **Describe the bug** I'm currently trying to deploy my Flask app using the Serverless framework and AWS Lambda. When the user logs in and is redirected to a frontend page that queries for user data using the returned `code` URL param, the API fails but does not return an error. **Your code** ``` IS_OFFLINE = os.environ.get('IS_OFFLINE') # Setting secret keys based on environment SPOTIFY_CLIENT_ID = config('SPOTIFY_CLIENT_ID') if IS_OFFLINE else os.environ['SPOTIFY_CLIENT_ID'] SPOTIFY_CLIENT_SECRET = config('SPOTIFY_CLIENT_SECRET') if IS_OFFLINE else os.environ['SPOTIFY_CLIENT_SECRET'] APP_SECRET_KEY = config('APP_SECRET_KEY') if IS_OFFLINE else os.environ['APP_SECRET_KEY'] # Setting URLs based on environment SETLISTIFY_CLIENT_BASE = 'http://localhost:3000' if IS_OFFLINE else PROD_URL REDIRECT_URI = f"{SETLISTIFY_CLIENT_BASE}/callback" SPOTIFY_API_BASE = 'https://accounts.spotify.com' SCOPE = 'playlist-modify-public' CACHE = '.spotipyoauthcache' app = Flask(__name__) app.debug = True app.config['SECRET_KEY'] = APP_SECRET_KEY app.config['SESSION_TYPE'] = 'filesystem' Session(app) CORS(app, supports_credentials=True) auth_manager = spotipy.oauth2.SpotifyOAuth(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, REDIRECT_URI, scope=SCOPE, cache_path=CACHE) spotify = spotipy.Spotify(auth_manager=auth_manager) @app.route("/authUrl") def verify(): authUrl = auth_manager.get_authorize_url() return jsonify({'authUrl': authUrl}) @app.route("/getUser", methods=['POST']) def get_user(): session.clear() code = request.json.get('code') session['token_info'] = auth_manager.get_access_token(code) results = spotify.current_user() return jsonify(results) ``` Frontend query ``` const body = JSON.stringify({ 'code': params.code }); fetch(`${fetchUrl()}/getUser`, { method: 'post', credentials: 'include', headers: {'Content-Type':'application/json'}, body: body }).then(res => res.json()) .then(data => { setUser(data); handleLogin(); }); ``` **Expected behavior** User data is returned via this request **Output** No errors are displayed in CloudWatch or in Serverless **Environment:** - OS: [Mac] - Python version [3.7.0] - spotipy version [2.13.0] - your IDE (if using any) [WebStorm] **Additional context** https://www.serverless.com/blog/flask-python-rest-api-serverless-lambda-dynamodb/ Used this to get started up with Flask/Lambda
kerem 2026-02-27 23:22:00 +03:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@alexcaulfield commented on GitHub (Jul 9, 2020):

I ended up leveraging JWT instead, so no issue here.

<!-- gh-comment-id:655876286 --> @alexcaulfield commented on GitHub (Jul 9, 2020): I ended up leveraging JWT instead, so no issue here.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/spotipy#324
No description provided.