Back

Step by Step Guide to Building a Delighted API Integration in Python

Aug 16, 20246 minute read

Introduction

Hey there, fellow developer! Ready to supercharge your customer feedback game? Let's dive into building a Delighted API integration in Python. Delighted's API is a powerhouse for gathering and analyzing customer feedback, and we're about to harness that power with some Python magic.

Prerequisites

Before we jump in, make sure you've got:

  • A Python environment (3.6+ recommended)
  • Your Delighted API key (if you don't have one, hop over to Delighted's website and grab it)

Installation

First things first, let's get our tools ready:

pip install requests

That's it! We're keeping it lean and mean with just the requests library.

Authentication

Alright, let's get you authenticated:

import requests API_KEY = 'your_api_key_here' BASE_URL = 'https://api.delighted.com/v1/' headers = { 'Authorization': f'Basic {API_KEY}', 'Accept': 'application/json' }

Pro tip: In a real-world scenario, keep that API key safe in an environment variable!

Basic API Requests

Let's flex those API muscles with some basic requests:

# GET request response = requests.get(f'{BASE_URL}metrics', headers=headers) print(response.json()) # POST request data = { 'email': '[email protected]', 'delay': 60 } response = requests.post(f'{BASE_URL}people', headers=headers, data=data) print(response.json())

Implementing Key Features

Now for the fun part - let's put this API to work!

Sending Surveys

def send_survey(email): data = {'email': email} response = requests.post(f'{BASE_URL}people', headers=headers, data=data) return response.json()

Retrieving Survey Responses

def get_survey_responses(): response = requests.get(f'{BASE_URL}survey_responses', headers=headers) return response.json()

Analyzing Survey Data

def analyze_nps(): responses = get_survey_responses() scores = [r['score'] for r in responses] return sum(scores) / len(scores)

Error Handling

Let's not let those pesky errors catch us off guard:

def api_request(method, endpoint, data=None): try: if method == 'GET': response = requests.get(f'{BASE_URL}{endpoint}', headers=headers) elif method == 'POST': response = requests.post(f'{BASE_URL}{endpoint}', headers=headers, data=data) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Oops! API request failed: {e}") return None

Rate Limiting

Delighted's got some speed limits, so let's play nice:

import time def rate_limited_request(method, endpoint, data=None): response = api_request(method, endpoint, data) if response and 'retry-after' in response.headers: retry_after = int(response.headers['retry-after']) print(f"Rate limit hit. Waiting for {retry_after} seconds...") time.sleep(retry_after) return rate_limited_request(method, endpoint, data) return response

Pagination

For when there's too much awesome data to fit in one response:

def get_all_responses(): all_responses = [] page = 1 while True: responses = api_request('GET', f'survey_responses?page={page}') if not responses: break all_responses.extend(responses) page += 1 return all_responses

Webhooks (Optional)

Want real-time updates? Set up a webhook endpoint in your app and configure it in your Delighted dashboard. Here's a quick Flask example:

from flask import Flask, request app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): data = request.json # Process the webhook data return '', 200

Testing

Don't forget to test your integration! Here's a simple unit test to get you started:

import unittest class TestDelightedIntegration(unittest.TestCase): def test_send_survey(self): result = send_survey('[email protected]') self.assertIn('person', result) if __name__ == '__main__': unittest.main()

Best Practices

  • Keep your code modular and well-documented
  • Use environment variables for sensitive info
  • Implement proper error logging
  • Consider using a rate limiting library for more complex scenarios

Conclusion

And there you have it! You've just built a robust Delighted API integration in Python. You're now armed with the power to send surveys, analyze responses, and gain valuable insights from your customers.

Remember, this is just the beginning. Feel free to expand on this foundation and tailor it to your specific needs. Happy coding, and may your NPS scores always be high!