Sobes.tech
Junior — Middle

What methods can be used to protect the application programming interface from unauthorized access?

sobes.tech AI

Answer from AI

To protect the application programming interface (API) from unauthorized access in Python, several approaches can be used:

  • Authentication and authorization: implement user verification using tokens (e.g., JWT), API keys, or OAuth.
  • IP access restriction: allow requests only from trusted IP addresses.
  • Data encryption: use HTTPS to protect data during transmission.
  • Rate limiting: prevent abuse by limiting the number of requests over a certain period.
  • Validation and filtering of incoming data: to prevent attacks like SQL injection or XSS.

An example of a simple API key check in Flask:

from flask import Flask, request, abort

app = Flask(__name__)
API_KEY = "secret_key"

@app.before_request
def check_api_key():
    key = request.headers.get('X-API-KEY')
    if key != API_KEY:
        abort(401)  # Unauthorized

@app.route('/data')
def data():
    return {"message": "Access granted"}

if __name__ == '__main__':
    app.run()

Thus, protection is achieved through a combination of methods, depending on security requirements.