0
0
Flaskframework~5 mins

Flask route as API endpoint

Choose your learning style9 modes available
Introduction

A Flask route lets you create a web address that your app listens to. Using it as an API endpoint means your app can send or receive data when someone visits that address.

You want to let other programs get data from your app.
You want to let other programs send data to your app.
You want to build a simple web service that returns information.
You want to connect your app with a frontend or mobile app.
You want to test your app by calling specific URLs.
Syntax
Flask
@app.route('/path', methods=['GET', 'POST'])
def function_name():
    # code to handle request
    return response

The @app.route decorator tells Flask which URL to listen to.

The methods list defines which HTTP actions the route accepts, like GET or POST.

Examples
A simple route that returns a greeting when you visit '/hello'. It only accepts GET requests by default.
Flask
@app.route('/hello')
def hello():
    return 'Hello, world!'
This route accepts POST requests with JSON data and sends back a confirmation with the data received.
Flask
from flask import request

@app.route('/data', methods=['POST'])
def receive_data():
    data = request.json
    return {'message': 'Data received', 'yourData': data}
Sample Program

This Flask app creates an API endpoint at '/api/greet'. It reads a name from the URL query and returns a friendly greeting in JSON format.

Flask
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/greet', methods=['GET'])
def greet():
    name = request.args.get('name', 'Guest')
    return jsonify({'message': f'Hello, {name}!'})

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always return JSON for API endpoints to keep data easy to use.

Use request.args for GET data and request.json for POST JSON data.

Run Flask with debug=True only during development to see helpful errors.

Summary

Flask routes create web addresses your app listens to.

Use routes as API endpoints to send or receive data.

Return JSON responses for easy data exchange.