In Python REST APIs, how do I expose a REST API?

In Python, you can expose a REST API using various frameworks, with Flask and FastAPI being some of the most popular choices. Below is an example using Flask, which is lightweight and easy to use.

To create a simple REST API using Flask, you need to first install Flask if you haven't already:

pip install Flask

Next, you can create a basic API that handles GET and POST requests:

from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/api/items', methods=['GET']) def get_items(): items = {"items": ["item1", "item2", "item3"]} return jsonify(items) @app.route('/api/items', methods=['POST']) def add_item(): new_item = request.json.get('item') # Here you would typically add the new item to a database return jsonify({"message": f"Item {new_item} added!"}), 201 if __name__ == '__main__': app.run(debug=True)

This example creates an API with two endpoints:

  • GET /api/items - Returns a list of items.
  • POST /api/items - Adds a new item to the list.

Once you run this script, you can test the API endpoints using tools like Postman or cURL.


Python REST API Flask FastAPI web development