Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flask REST API - Echo

from flask import Flask, request
from flask_restful import Api, Resource

app = Flask(__name__)

api = Api(app)

class Echo(Resource):
    def get(self):
        user_text = request.args.get('text', '')
        return { "echo": user_text, "method": "GET" }
    def post(self):
        user_text = request.form.get('text', '')
        return { "echo": user_text, "method": "POST" }

api.add_resource(Echo, '/echo')

import api
import pytest

@pytest.fixture()
def web():
    return api.app.test_client()

def test_echo_get_empty(web):
    rv = web.get('/echo')
    assert rv.status == '200 OK'
    assert rv.headers['Content-Type'] == 'application/json'
    assert rv.json == {"echo": "", "method": "GET"}

def test_echo_get_text(web):
    rv = web.get('/echo?text=One+Two+Three')
    assert rv.status == '200 OK'
    assert rv.headers['Content-Type'] == 'application/json'
    assert rv.json == {"echo": "One Two Three", "method": "GET"}


def test_echo_post_empty(web):
    rv = web.post('/echo')
    assert rv.status == '200 OK'
    assert rv.headers['Content-Type'] == 'application/json'
    assert rv.json == {"echo": "", "method": "POST"}

def test_echo_post_text(web):
    rv = web.post('/echo', data={"text": "Happy Path"})
    assert rv.status == '200 OK'
    assert rv.headers['Content-Type'] == 'application/json'
    assert rv.json == {"echo": "Happy Path", "method": "POST"}


def test_main_page(web):
    rv = web.get('/')
    assert rv.status == '404 NOT FOUND'
    assert rv.headers['Content-Type'] == 'text/html; charset=utf-8'
    assert b'<title>404 Not Found</title>' in rv.data


flask --app api run

GET request

$ curl -i http://localhost:5000/echo?text=Hello+World!
HTTP/1.1 200 OK
Server: Werkzeug/3.1.6 Python/3.13.7
Date: Sat, 28 Mar 2026 19:50:13 GMT
Content-Type: application/json
Content-Length: 42
Connection: close

{"echo": "Hello World!", "method": "GET"}

POST request

$ curl -i -X POST -d 'text=Dear+Flask' http://localhost:5000/echo
HTTP/1.1 200 OK
Server: Werkzeug/3.1.6 Python/3.13.7
Date: Sat, 28 Mar 2026 19:51:40 GMT
Content-Type: application/json
Content-Length: 41
Connection: close

{"echo": "Dear Flask", "method": "POST"}