APIs let different programs talk to each other easily. They help apps share data and work together without confusion.
0
0
Why APIs matter in Flask
Introduction
You want your app to get data from another service, like weather info.
You want to let other apps use your app's features safely.
You want to connect your mobile app with your website's data.
You want to automate tasks by linking different software.
You want to build a system where parts work independently but communicate.
Syntax
Flask
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/api/data', methods=['GET']) def get_data(): data = {'message': 'Hello from API!'} return jsonify(data) if __name__ == '__main__': app.run(debug=True)
Use @app.route to define API endpoints.
jsonify() sends data in a format apps understand (JSON).
Examples
This example creates a simple API that returns a greeting message.
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.route('/api/hello') def hello(): return jsonify({'greeting': 'Hi there!'})
This API receives data from the user and sends it back, showing how to handle POST requests.
Flask
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/api/echo', methods=['POST']) def echo(): data = request.json return jsonify({'you_sent': data})
Sample Program
This Flask app has two API endpoints. One sends a welcome message when you visit /api/welcome. The other accepts a name in a POST request to /api/greet and replies with a personalized greeting.
Flask
from flask import Flask, jsonify, request app = Flask(__name__) # Simple API endpoint that returns a welcome message @app.route('/api/welcome') def welcome(): return jsonify({'message': 'Welcome to our API!'}) # API endpoint that accepts a name and returns a greeting @app.route('/api/greet', methods=['POST']) def greet(): data = request.json name = data.get('name', 'Guest') return jsonify({'greeting': f'Hello, {name}!'}) if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
APIs usually send data in JSON format because it's easy to read and use.
Use HTTP methods like GET to get data and POST to send data.
Testing APIs can be done with tools like Postman or browser for GET requests.
Summary
APIs help apps share data and features easily.
Flask makes it simple to create APIs with routes and JSON responses.
APIs use standard methods like GET and POST to communicate.