Restful Api & Flask Assignment
Restful Api & Flask Assignment
THEORY
1. What is a RESTful API?
- A RESTful API (Representational State Transfer API) is a web
service that follows REST principles, using standard HTTP
methods like GET, POST, PUT, and DELETE to enable
communication between clients and servers.
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
○ POST: Submits data to the server, often used for creating resources.
@app.errorhandler(404)
def not_found(error):
return jsonify({"error": "Not Found"}), 404
10. How do you connect Flask to a SQL database?
Use Flask-SQLAlchemy:
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({"message": "Hello, API!"})
if __name__ == '__main__':
app.run()
19.What are HTTP status codes, and why are they important in a
Flask API?
They indicate request outcomes (e.g., 200 OK, 404 Not
Found, 500 Internal Server Error).
@app.route('/submit', methods=['POST'])
def submit():
data = request.json
return jsonify(data), 201
21.How would you secure a Flask API?
○ Enable HTTPS.