Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
Python - Variable declarations
Conditional Statements in Python
Loops in Python
Python Functions
Python Classes
OOPS in Python
Python - Hello World Application
Python - import statements
Python - Web API

Python - Web API



Creating a web API in Python is a great way to expose your application's functionality to other applications or users over the web. One of the most popular frameworks for building web APIs in Python is Flask. Flask is lightweight and easy to use, making it ideal for developing simple to medium-sized web applications.

Getting Started with Flask

  1. Install Flask: First, you need to install Flask. You can do this using pip:

    sh
    pip install flask
    
  2. Create a Simple Web API: Let's create a simple web API that handles basic HTTP requests. We'll create an API that returns a greeting message.

    Example:

    python
    from flask import Flask, jsonify, request
    
    app = Flask(__name__)
    
    @app.route('/hello', methods=['GET'])
    def hello_world():
        return jsonify(message="Hello, World!")
    
    if __name__ == '__main__':
        app.run(debug=True)
    
    • @app.route('/hello', methods=['GET']): Defines a route that listens for GET requests at the /hello endpoint.

    • jsonify(): Converts the response to JSON format.

    • app.run(debug=True): Starts the Flask development server with debugging enabled.

  3. Run the Web API: Save the code to a file (e.g., app.py) and run it using Python:

    sh
    python app.py
    

    Your web API should now be running at http://127.0.0.1:5000/hello. You can test it by opening this URL in your web browser or using a tool like curl or Postman.

Adding More Endpoints

You can add more endpoints to your web API by defining additional routes. Let's add a POST endpoint that echoes the data sent in the request.

Example:

python
@app.route('/echo', methods=['POST'])
def echo():
    data = request.json
    return jsonify(data)

Example with a More Complex API

Let's create a more complex web API that simulates a simple to-do list application. We'll add endpoints to get, create, update, and delete to-do items.

Example:

python
from flask import Flask, jsonify, request

app = Flask(__name__)

todos = []

@app.route('/todos', methods=['GET'])
def get_todos():
    return jsonify(todos)

@app.route('/todos', methods=['POST'])
def create_todo():
    todo = request.json
    todos.append(todo)
    return jsonify(todo), 201

@app.route('/todos/<int:todo_id>', methods=['PUT'])
def update_todo(todo_id):
    todo = request.json
    todos[todo_id] = todo
    return jsonify(todo)

@app.route('/todos/<int:todo_id>', methods=['DELETE'])
def delete_todo(todo_id):
    todos.pop(todo_id)
    return '', 204

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

Explanation

  • GET /todos: Returns the list of to-do items.

  • POST /todos: Creates a new to-do item and adds it to the list.

  • PUT /todos/<int:todo_id>: Updates a specific to-do item based on its ID.

  • DELETE /todos/<int:todo_id>: Deletes a specific to-do item based on its ID.

Running the API

Save the code to a file (e.g., app.py) and run it using Python:

sh
python app.py

Your web API should now be running at http://127.0.0.1:5000. You can test the endpoints using tools like curl, Postman, or even a web browser.

Summary

By using Flask, you can quickly and easily create web APIs in Python. Flask's simplicity and flexibility make it a great choice for developing web applications and APIs.

If you have any specific questions or need further examples, feel free to ask!




All rights reserved | Privacy Policy | Sitemap