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 - parameters in path

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)

api = Api(app)

class Echo(Resource):
    def get(self, text):
        return { "GET response": f"Text: {text}" }

    def post(self, text):
        return { "POST response": f"Text: {text}" }


api.add_resource(Echo, '/echo/<text>')

import api
import pytest

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


def test_get(web):
    rv = web.get('/echo/hello')
    assert rv.status == '200 OK'
    assert rv.headers['Content-Type'] == 'application/json'
    assert rv.json ==  {'GET response': 'Text: hello'}

def test_post(web):
    rv = web.post('/echo/ciao')
    assert rv.status == '200 OK'
    assert rv.headers['Content-Type'] == 'application/json'
    assert rv.json == {'POST response': 'Text: ciao'}