apitoolkit-flask


Nameapitoolkit-flask JSON
Version 0.3.0 PyPI version JSON
download
home_page
SummaryAPIToolkit SDK for Flask
upload_time2024-03-13 07:39:33
maintainer
docs_urlNone
authorAPIToolkit
requires_python>=3.8
licenseMIT License Copyright (c) 2023 APIToolkit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords api apitoolkit observability api monitoring
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # API Toolkit Python Flask SDK

The API Toolkit Flask client is an sdk used to integrate flask web services with APIToolkit.
It monitors incoming traffic, gathers the requests and sends the request to the apitoolkit servers.

## Design decisions:

- Use the gcp SDK to send real time traffic from REST APIs to the gcp topic

## How to Integrate:

First install the apitoolkit flask sdk:
`pip install apitoolkit-flask`

Then add apitoolkit to your app like so (flask example):

```python
from flask import Flask
from apitoolkit_flask import APIToolkit

app = Flask(__name__)

apitoolkit = APIToolkit(api_key="<API_KEY>", debug=True)


@app.before_request
def before_request():
    apitoolkit.beforeRequest()

@app.after_request
def after_request(response):
    apitoolkit.afterRequest(response)
    return response


@app.route('/hello', methods=['GET', 'POST'])
def sample_route(subject):
    return {"Hello": "World"}

app.run(debug=True)

```

This will monitor all requests and send them to the APIToolkit's servers.

## Client Redacting fields

While it's possible to mark a field as redacted from the apitoolkit dashboard, this client also supports redacting at the client side.
Client side redacting means that those fields would never leave your servers at all. So you feel safer that your sensitive data only stays on your servers.

To mark fields that should be redacted, add them to the APIToolkit constructor.
Eg:

```python
from flask import Flask
from apitoolkit_flask import APIToolkit

app = Flask(__name__)

# A list of fields to redact from response body
redact_res = ["$.api_key", "$.password"]
# A list of fields to redact from request body
redact_req = ["$.credit-card.cvv", "$.credit-card.name"]
# A list of fields to redact from request and repsonse headers
redact_headers = ["Authorization", "Cookie"]

apitoolkit = APIToolkit(api_key="<API_KEY>", debug=True,redact_response_body=redact_res, redact_request_body=redact_req,redact_headers=redact_headers)

@app.before_request
def before_request():
    apitoolkit.beforeRequest()

@app.after_request
def after_request(response):
    apitoolkit.afterRequest(response)
    return response


@app.route('/hello', methods=['GET', 'POST'])
def sample_route(subject):
    return {"Hello": "World"}

app.run(debug=True)
```

It is important to note that while the `redact_headers` config field accepts a list of headers(case insensitive),
the `redact_request_body` and `redact_response_body` expect a list of JSONPath strings as arguments.

The choice of JSONPath was selected to allow you have great flexibility in descibing which fields within your responses are sensitive.
Also note that these list of items to be redacted will be aplied to all endpoint requests and responses on your server.
To learn more about jsonpath to help form your queries, please take a look at this cheatsheet:
[https://lzone.de/cheat-sheet/JSONPath](https://lzone.de/cheat-sheet/JSONPath)

## Tags and Service Versions

Enhance your request monitoring in APIToolkit by including tags and specifying service versions in the APIToolkit class constructor.

#### Example

```python
apitoolkit = APIToolkit(api_key="<API_KEY>", debug=True, service_version="3.0.0", tags=["prod", "eu"])
```

# Outgoing Requests

Effectively monitor outgoing HTTP requests from your Flask application using the `observe_request` function from the `apitoolkit_flask` module. This function allows you to capture and forward copies of both incoming and outgoing requests to an APIToolkit server for thorough monitoring and analysis.

### Example

```python
from flask import Flask, request
from apitoolkit_flask import observe_request

@app.route('/sample/<subject>', methods=['GET', 'POST'])
async def sample_route(subject):
    # Observe the request and send it to the APIToolkit server
    resp = observe_request(request).get("https://jsonplaceholder.typicode.com/todos/2")
    return resp.read()
```

The `observe_request` function wraps an HTTPX client, allowing you to use it seamlessly for any request, just like you would with HTTPX.

# Error Reporting

If you're familiar with sentry, bugsnag, or rollbar, you'll easily grasp this use case. However, with APIToolkit, errors are always linked to a parent request, enabling you to query and associate errors that occurred while serving a specific customer request.

## Reporting unhandled exceptions

To report unhandled exceptions that happened during a request, you can use the `handle_error` method on the APIToolkit class in your errorHandler function

### Example

```python
from flask import Flask
from apitoolkit_flask import APIToolkit

app = Flask(__name__)
apitoolkit = APIToolkit(api_key="<API_KEY>", debug=True)

@app.before_request
def before_request():
    apitoolkit.beforeRequest()

@app.after_request
def after_request(response):
    apitoolkit.afterRequest(response)
    return response

@app.errorhandler(Exception)
def handle_exception(e):
    apitoolkit.handle_error(e)
    # now handle the error how you please.
    return {"message": "something went wrong"}, 500

@app.route('/hello', methods=['GET', 'POST'])
def sample_route(subject):
    return {"Hello": "World"}

app.run(debug=True)
```

### Report handled errors

You can also report handled errors to APIToolkit, utilize the `report_error` function from the `apitoolkit_flask` module. You can report as many errors as needed during a request.

### Example

```python
from flask import Flask, request
from apitoolkit_flask import observe_request, report_error

@app.route('/sample/<subject>', methods=['GET', 'POST'])
async def sample_route(subject):
    try:
        resp = observe_request(request).get("https://jsonplaceholder.typicode.com/todos/2")
        return resp.read()
    except Exception as e:
        # Report the error to APIToolkit
        report_error(request, e)
        return "Something went wrong"
```

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "apitoolkit-flask",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "API,APIToolkit,Observability,API Monitoring",
    "author": "APIToolkit",
    "author_email": "Anthony ALaribe <anthonyalaribe@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/c0/63/64a4097f198cc3f2caf80bfa3f9ad2f9061705d871a33160634d558d2176/apitoolkit-flask-0.3.0.tar.gz",
    "platform": null,
    "description": "# API Toolkit Python Flask SDK\n\nThe API Toolkit Flask client is an sdk used to integrate flask web services with APIToolkit.\nIt monitors incoming traffic, gathers the requests and sends the request to the apitoolkit servers.\n\n## Design decisions:\n\n- Use the gcp SDK to send real time traffic from REST APIs to the gcp topic\n\n## How to Integrate:\n\nFirst install the apitoolkit flask sdk:\n`pip install apitoolkit-flask`\n\nThen add apitoolkit to your app like so (flask example):\n\n```python\nfrom flask import Flask\nfrom apitoolkit_flask import APIToolkit\n\napp = Flask(__name__)\n\napitoolkit = APIToolkit(api_key=\"<API_KEY>\", debug=True)\n\n\n@app.before_request\ndef before_request():\n    apitoolkit.beforeRequest()\n\n@app.after_request\ndef after_request(response):\n    apitoolkit.afterRequest(response)\n    return response\n\n\n@app.route('/hello', methods=['GET', 'POST'])\ndef sample_route(subject):\n    return {\"Hello\": \"World\"}\n\napp.run(debug=True)\n\n```\n\nThis will monitor all requests and send them to the APIToolkit's servers.\n\n## Client Redacting fields\n\nWhile it's possible to mark a field as redacted from the apitoolkit dashboard, this client also supports redacting at the client side.\nClient side redacting means that those fields would never leave your servers at all. So you feel safer that your sensitive data only stays on your servers.\n\nTo mark fields that should be redacted, add them to the APIToolkit constructor.\nEg:\n\n```python\nfrom flask import Flask\nfrom apitoolkit_flask import APIToolkit\n\napp = Flask(__name__)\n\n# A list of fields to redact from response body\nredact_res = [\"$.api_key\", \"$.password\"]\n# A list of fields to redact from request body\nredact_req = [\"$.credit-card.cvv\", \"$.credit-card.name\"]\n# A list of fields to redact from request and repsonse headers\nredact_headers = [\"Authorization\", \"Cookie\"]\n\napitoolkit = APIToolkit(api_key=\"<API_KEY>\", debug=True,redact_response_body=redact_res, redact_request_body=redact_req,redact_headers=redact_headers)\n\n@app.before_request\ndef before_request():\n    apitoolkit.beforeRequest()\n\n@app.after_request\ndef after_request(response):\n    apitoolkit.afterRequest(response)\n    return response\n\n\n@app.route('/hello', methods=['GET', 'POST'])\ndef sample_route(subject):\n    return {\"Hello\": \"World\"}\n\napp.run(debug=True)\n```\n\nIt is important to note that while the `redact_headers` config field accepts a list of headers(case insensitive),\nthe `redact_request_body` and `redact_response_body` expect a list of JSONPath strings as arguments.\n\nThe choice of JSONPath was selected to allow you have great flexibility in descibing which fields within your responses are sensitive.\nAlso note that these list of items to be redacted will be aplied to all endpoint requests and responses on your server.\nTo learn more about jsonpath to help form your queries, please take a look at this cheatsheet:\n[https://lzone.de/cheat-sheet/JSONPath](https://lzone.de/cheat-sheet/JSONPath)\n\n## Tags and Service Versions\n\nEnhance your request monitoring in APIToolkit by including tags and specifying service versions in the APIToolkit class constructor.\n\n#### Example\n\n```python\napitoolkit = APIToolkit(api_key=\"<API_KEY>\", debug=True, service_version=\"3.0.0\", tags=[\"prod\", \"eu\"])\n```\n\n# Outgoing Requests\n\nEffectively monitor outgoing HTTP requests from your Flask application using the `observe_request` function from the `apitoolkit_flask` module. This function allows you to capture and forward copies of both incoming and outgoing requests to an APIToolkit server for thorough monitoring and analysis.\n\n### Example\n\n```python\nfrom flask import Flask, request\nfrom apitoolkit_flask import observe_request\n\n@app.route('/sample/<subject>', methods=['GET', 'POST'])\nasync def sample_route(subject):\n    # Observe the request and send it to the APIToolkit server\n    resp = observe_request(request).get(\"https://jsonplaceholder.typicode.com/todos/2\")\n    return resp.read()\n```\n\nThe `observe_request` function wraps an HTTPX client, allowing you to use it seamlessly for any request, just like you would with HTTPX.\n\n# Error Reporting\n\nIf you're familiar with sentry, bugsnag, or rollbar, you'll easily grasp this use case. However, with APIToolkit, errors are always linked to a parent request, enabling you to query and associate errors that occurred while serving a specific customer request.\n\n## Reporting unhandled exceptions\n\nTo report unhandled exceptions that happened during a request, you can use the `handle_error` method on the APIToolkit class in your errorHandler function\n\n### Example\n\n```python\nfrom flask import Flask\nfrom apitoolkit_flask import APIToolkit\n\napp = Flask(__name__)\napitoolkit = APIToolkit(api_key=\"<API_KEY>\", debug=True)\n\n@app.before_request\ndef before_request():\n    apitoolkit.beforeRequest()\n\n@app.after_request\ndef after_request(response):\n    apitoolkit.afterRequest(response)\n    return response\n\n@app.errorhandler(Exception)\ndef handle_exception(e):\n    apitoolkit.handle_error(e)\n    # now handle the error how you please.\n    return {\"message\": \"something went wrong\"}, 500\n\n@app.route('/hello', methods=['GET', 'POST'])\ndef sample_route(subject):\n    return {\"Hello\": \"World\"}\n\napp.run(debug=True)\n```\n\n### Report handled errors\n\nYou can also report handled errors to APIToolkit, utilize the `report_error` function from the `apitoolkit_flask` module. You can report as many errors as needed during a request.\n\n### Example\n\n```python\nfrom flask import Flask, request\nfrom apitoolkit_flask import observe_request, report_error\n\n@app.route('/sample/<subject>', methods=['GET', 'POST'])\nasync def sample_route(subject):\n    try:\n        resp = observe_request(request).get(\"https://jsonplaceholder.typicode.com/todos/2\")\n        return resp.read()\n    except Exception as e:\n        # Report the error to APIToolkit\n        report_error(request, e)\n        return \"Something went wrong\"\n```\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2023 APIToolkit  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "APIToolkit SDK for Flask",
    "version": "0.3.0",
    "project_urls": {
        "Homepage": "https://github.com/apitoolkit/apitoolkit-flask"
    },
    "split_keywords": [
        "api",
        "apitoolkit",
        "observability",
        "api monitoring"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c06364a4097f198cc3f2caf80bfa3f9ad2f9061705d871a33160634d558d2176",
                "md5": "cae643afb1d2a75e6e97d00bff5f30af",
                "sha256": "354e14f2c160617014056c292bf35729bdebf855a45f8cb423d17b3ee52deb34"
            },
            "downloads": -1,
            "filename": "apitoolkit-flask-0.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "cae643afb1d2a75e6e97d00bff5f30af",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 8363,
            "upload_time": "2024-03-13T07:39:33",
            "upload_time_iso_8601": "2024-03-13T07:39:33.260218Z",
            "url": "https://files.pythonhosted.org/packages/c0/63/64a4097f198cc3f2caf80bfa3f9ad2f9061705d871a33160634d558d2176/apitoolkit-flask-0.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-13 07:39:33",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "apitoolkit",
    "github_project": "apitoolkit-flask",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "apitoolkit-flask"
}
        
Elapsed time: 0.20579s