Loading

Quipoin Menu

Learn • Practice • Grow

flask / API Authentication
tutorial

API Authentication

APIs often need to authenticate users. A common method is token‑based authentication, where the client sends a token (e.g., JWT) in the `Authorization` header.

Installing JWT Library

pip install pyjwt

Generate Token on Login

import jwt
import datetime

@app.route('/api/login', methods=['POST'])
def api_login():
data = request.get_json()
user = User.query.filter_by(username=data['username']).first()
if user and check_password_hash(user.password, data['password']):
token = jwt.encode({
'user_id': user.id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24)
}, app.config['SECRET_KEY'], algorithm='HS256')
return jsonify({'token': token})
return jsonify({'error': 'Invalid credentials'}), 401

Token Verification Decorator

def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'error': 'Token missing'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
current_user = User.query.get(data['user_id'])
except:
return jsonify({'error': 'Invalid token'}), 401
return f(current_user, *args, **kwargs)
return decorated

Protecting Routes with Token

@app.route('/api/protected')
@token_required
def protected(current_user):
return jsonify({'message': f'Hello {current_user.username}'})

Client Request with Token

curl -H "Authorization: " http://localhost:5000/api/protected


Two Minute Drill
  • JWT tokens are stateless and contain user info.
  • Send token in `Authorization` header.
  • Create a decorator to verify token on protected routes.
  • Set token expiration for security.

Need more clarification?

Drop us an email at career@quipoinfotech.com