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 - Hello World

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

class Hello(Resource):
    def get(self):
        return { "message": "GET - Restful Flask" }
    def post(self):
        return { "message": "POST - Restful Flask" }

api.add_resource(Hello, '/api/hello')

import api
import pytest

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

def test_echo_get(web):
    rv = web.get('/api/hello')
    assert rv.status == '200 OK'
    assert rv.headers['Content-Type'] == 'application/json'
    assert rv.json == {"message": "GET - Restful Flask"}

def test_echo_post(web):
    rv = web.post('/api/hello')
    assert rv.status == '200 OK'
    assert rv.headers['Content-Type'] == 'application/json'
    assert rv.json == {"message": "POST - Restful Flask"}

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/api/hello
HTTP/1.1 200 OK
Server: Werkzeug/3.1.6 Python/3.13.7
Date: Sat, 28 Mar 2026 19:42:26 GMT
Content-Type: application/json
Content-Length: 35
Connection: close

{"message": "GET - Restful Flask"}

POST request

$ curl -i -X POST http://localhost:5000/api/hello
HTTP/1.1 200 OK
Server: Werkzeug/3.1.6 Python/3.13.7
Date: Sat, 28 Mar 2026 19:43:19 GMT
Content-Type: application/json
Content-Length: 36
Connection: close

{"message": "POST - Restful Flask"}