Interacting with External APIs

INFO 153B/253B: Backend Web Architecture

Kay Ashaolu

What is an External API?

  • Any service that is outside of your current system
  • In our case, any system that is not managed by your docker-compose.yml file is an external API
  • In your Assignments, terminal-chatbot is treating your system as an external API

What is an External API?

  • Any service that is outside of your current system
  • In our case, any system that is not managed by your docker-compose.yml file is an external API
  • In your Assignments, terminal-chatbot is treating your system as an external API

What is an External API?

  • You do not (typically) have any control over the implementation of the external API
  • All you know is whatever the documentation provides you
  • As long as it provides the following for pieces of information:
    • The name of the endpoint
    • What the endpoint does
    • The input/parameters that it requests
    • The output
  • You can use the external API (just like you can use a function)

External API examples

  • Database: using Google Realtime Database as a key-value store so you don't have to manage data in your system. Gain realtime syncing across all 
  • Functional: using a API like SendGrid to send emails via HTTP API call instead of having to manage your own SMTP email servers
  • Workflow: creating a workflow on a site like Zapier enables you to create an API that connects thousands of services together that can be accessed via HTTP API

Power of External APIs

  • External APIs harness the power of the cloud
  • You can easily add robust extra functionality as easily as sending HTTP requests to that external API

 

This is the power of the cloud

Process of finding and integrating External APIs

  • Research is important just like looking for any other service online
  • Ensure that the external API is reliable and if it stores your data and protects your data
  • Tradeoff in using External API: now some activity/data is stored outside of your system, so if a security breach or downtime occurs in the external system, it can affect your system
  • There are ways to mitigate external API dependencies like using asynchronous task queues that keep your system going despite external failures

Steps

  1. Find a secure and reliable API. Check reviews from actual users.
  2. Sign up for the site. You may need to add 2-factor authentication (learn how to use an authenticator app on your phone
  3. Find out how you are supposed to construct the HTTP request to use the API. Sometimes the API has a client package (written in Python or other languages) that you can use instead of having to construct the HTTP request yourself
  4. Create whatever authentication mechanism they need (if any). Most of the time this requires creating an API key on the service that you use in your code
  5. Integrate the sample code they provide to your system

Example: Sendgrid

Example: Sendgrid

  • docker-compose.yml
version: "3.7"
services:
  email-service:
    build: ./email-service/
    image: email-service-image
    ports:
      - "5050:5000"
    environment:
      SENDGRID_API_KEY: ADD_YOUR_API_KEY_FROM_SENDGRID_HERE

Example: Sendgrid

  • email-service/send_email_server.py (1/2)
from flask import Flask, request
import json
import logging
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

app = Flask(__name__)

@app.route('/email', methods = ['POST'])
def quote_of_the_day_post():

    if request.headers.get("Content-Type") == 'application/json':

        data = request.get_json()
        to_email = data.get("to")
        from_email = data.get("from")
        subject = data.get("subject")
        body = data.get("body")

        if not to_email or not from_email or not subject or not body:
            response = {"message": "Please fill out all fields to send an email"}
            response_code = 400           
        else:
            message = Mail(
                from_email=from_email,
                to_emails=to_email,
                subject=subject,
                html_content=body)
            try:
                sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
                sg.send(message)
                response = {"message": "Email was sent"}
                response_code = 200
            except Exception as e:
                logging.error(e)
    else:
        response = {"message": "Endpoint requires json input"}
        response_code = 400 
    
    return json.dumps(response), response_code
        

Example: Sendgrid

  • email-service/send_email_server.py (2/2)
        if not to_email or not from_email or not subject or not body:
            response = {"message": "Please fill out all fields to send an email"}
            response_code = 400           
        else:
            message = Mail(
                from_email=from_email,
                to_emails=to_email,
                subject=subject,
                html_content=body)
            try:
                sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
                sg.send(message)
                response = {"message": "Email was sent"}
                response_code = 200
            except Exception as e:
                logging.error(e)
    else:
        response = {"message": "Endpoint requires json input"}
        response_code = 400 
    
    return json.dumps(response), response_code
        

Questions?