Junior — Middle
What approaches and principles do you use when developing API interfaces?
sobes.tech AI
Answer from AI
When developing APIs, I adhere to the following principles:
- RESTful approach: using standard HTTP methods (GET, POST, PUT, DELETE) and a clear URL structure.
- Idempotency and security: methods that should not change the state only perform read operations (GET), while modifying methods handle repeated requests correctly.
- Clear documentation: using OpenAPI/Swagger to describe interfaces.
- Error handling: returning understandable and standardized error codes and messages.
- API versioning: to avoid breaking clients during updates.
- Authentication and authorization: for example, via OAuth or JWT.
Example of a simple Flask API:
from flask import Flask, jsonify, request
app = Flask(__name__)
items = {1: 'item1', 2: 'item2'}
@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
item = items.get(item_id)
if item:
return jsonify({'id': item_id, 'name': item}), 200
else:
return jsonify({'error': 'Item not found'}), 404
if __name__ == '__main__':
app.run()