1. Home
  2. /
  3. Flask
  4. /
  5. Simple Counter API

Simple Counter API - Flask Typing CST Test

Loading…

Simple Counter API — Flask Code

Demonstrates a simple Flask app with a counter API and HTML interface using routes and global state.

from flask import Flask, render_template_string, request

app = Flask(__name__)
count = 0

TEMPLATE = '''
<!DOCTYPE html>
<html>
<head><title>Flask Counter</title></head>
<body>
	<h2>Counter: {{ count }}</h2>
	<form method='post'>
		<button name='action' value='increment'>+</button>
		<button name='action' value='decrement'>-</button>
		<button name='action' value='reset'>Reset</button>
	</form>
</body>
</html>
'''

@app.route('/', methods=['GET', 'POST'])
def counter():
	global count
	if request.method == 'POST':
		action = request.form.get('action')
		if action == 'increment': count += 1
		elif action == 'decrement': count -= 1
		elif action == 'reset': count = 0
	return render_template_string(TEMPLATE, count=count)

if __name__ == '__main__':
	app.run(debug=True, port=5000)

Flask Language Guide

Flask is a lightweight, WSGI-based web framework for Python. It emphasizes simplicity, flexibility, and minimalism, allowing developers to build web applications and APIs quickly without imposing a specific project structure.

Primary Use Cases

  • ▸RESTful API development
  • ▸Backend for web/mobile applications
  • ▸Microservices architecture
  • ▸Prototyping and MVP development
  • ▸Serving dynamic web content using templates

Notable Features

  • ▸Lightweight and minimalistic core
  • ▸Extensible via Flask extensions
  • ▸Built-in development server and debugger
  • ▸URL routing and request handling
  • ▸Jinja2 template engine for rendering HTML

Origin & Creator

Flask was created by Armin Ronacher in 2010 as part of the Pocoo project, aiming to provide a simple and extensible Python web framework.

Industrial Note

Flask is preferred for projects requiring flexibility, lightweight architecture, or microservices without the overhead of larger frameworks like Django.

More Flask Typing Exercises

Flask Hello World APIFlask JSON EchoFlask Query Parameter ExampleFlask Route Parameter ExampleFlask Middleware ExampleFlask Async ExampleFlask Error Handling ExampleFlask Combined Middleware and RoutesFlask Template Example

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher