Slide 1

Slide 1 text

There’s an API for that! PyCon Colombia 2022 Mariatta

Slide 2

Slide 2 text

Mariatta Python Core Developer Senior Developer Relations Engineer @ Google Vancouver, Canada She/her UTC-7 @mariatta There’s an API for that! @mariatta PyCon Colombia 2022

Slide 3

Slide 3 text

Bots of Python the-knights-who-say-ni bedevere-bot miss-islington blurb-it There’s an API for that! @mariatta PyCon Colombia 2022

Slide 4

Slide 4 text

I once applied for a job and was told to “build a bot” and I didn’t know how to do it There’s an API for that! @mariatta PyCon Colombia 2022

Slide 5

Slide 5 text

What even is a bot? There’s an API for that! @mariatta PyCon Colombia 2022

Slide 6

Slide 6 text

There’s an API for that! @mariatta GitHub Bot PyCon Colombia 2022

Slide 7

Slide 7 text

Gitter Bot There’s an API for that! @mariatta PyCon Colombia 2022

Slide 8

Slide 8 text

Bot == ? There’s an API for that! @mariatta PyCon Colombia 2022

Slide 9

Slide 9 text

Bot == Web App There’s an API for that! @mariatta PyCon Colombia 2022

Slide 10

Slide 10 text

Bot == Web App == Automation There’s an API for that! @mariatta PyCon Colombia 2022

Slide 11

Slide 11 text

• Wait for PR to be opened • Automatically post a comment • Automatically apply a label • Check data against database There’s an API for that! @mariatta PyCon Colombia 2022

Slide 12

Slide 12 text

• Wait for a message • If it is a message for robot, then post a message There’s an API for that! @mariatta PyCon Colombia 2022

Slide 13

Slide 13 text

There’s an API for that! @mariatta Third Party API Your Web App The internet PyCon Colombia 2022

Slide 14

Slide 14 text

There’s an API for that! @mariatta Third Party API calls Your Web App PyCon Colombia 2022

Slide 15

Slide 15 text

There’s an API for that! @mariatta Your Web App Third Party Webhooks (Incoming API calls) PyCon Colombia 2022

Slide 16

Slide 16 text

There’s an API for that! @mariatta Your Web App Third Party Webhooks API calls a.k.a bot PyCon Colombia 2022

Slide 17

Slide 17 text

Working with APIs There’s an API for that! @mariatta PyCon Colombia 2022

Slide 18

Slide 18 text

Read the Documentation • Also called Developer docs • Start with Tutorials if you’re new (but they don’t always have this) • API endpoints are listed under Resources There’s an API for that! @mariatta PyCon Colombia 2022

Slide 19

Slide 19 text

Read the Documentation • Also called Developer docs • Start with Tutorials if you’re new (but they don’t always have this) • API endpoints are listed under Resources There’s an API for that! @mariatta PyCon Colombia 2022

Slide 20

Slide 20 text

Authentication • API keys or OAuth2 • Keep your credentials secret! • Don’t store as plain text • Don’t commit to your codebase • Use environment variables There’s an API for that! @mariatta PyCon Colombia 2022 # DON'T DO THIS TOKEN = "my token" # DO THIS import os TOKEN = os.environ["TOKEN"]

Slide 21

Slide 21 text

Use Client Libraries • Helper library for working with third-party APIs • Also called toolkit or SDKs or wrappers • Abstraction and simpli f ication. • Hides details of request authorization, headers, signature veri f ication • Write code in your favourite language (e.g. Python) • No client library? Write one! • Use Swagger client if they have OpenAPI There’s an API for that! @mariatta PyCon Colombia 2022

Slide 22

Slide 22 text

Webhooks • Use your favourite web framework • Django REST framework, Flask, FastAPI, aiohttp, etc. • Always verify incoming requests • Sometimes they use secrets • Sometimes they’d pass speci f ic header • The client library should provide this. If not, f ile a feature request! There’s an API for that! @mariatta PyCon Colombia 2022

Slide 23

Slide 23 text

There’s an API for that! There’s an API for that! @mariatta Don’t Scrape PyCon Colombia 2022

Slide 24

Slide 24 text

GitHub APIs There’s an API for that! @mariatta PyCon Colombia 2022

Slide 25

Slide 25 text

GitHub APIs • Dev Docs: https://docs.github.com/en/developers • Authentication using personal access token or OAuth2 • O ff icial Client Libraries: in Ruby, .NET, JavaScript • Third party Python library: https://gidgethub.readthedocs.io/ • My GitHub App tutorial: https://github-app-tutorial.readthedocs.io/ There’s an API for that! @mariatta PyCon Colombia 2022 > python3 -m pip install gidgethub

Slide 26

Slide 26 text

GitHub APIs response = await gh.post( f'/repos/{owner}/{repo}/issues ', data={ 'title': 'Found a bug!', 'body': 'Use more emoji!', } ) API for opening an issue Using gidgethub There’s an API for that! @mariatta PyCon Colombia 2022

Slide 27

Slide 27 text

GitHub APIs Webhook event handler Using gidgethub @router.register("issue", action="opened") async def issue_opened(event, gh, *args, **kwargs): ... response = await gh.post( f"{issue_url}/comments", data={"body": msg}, oauth_token=installation_access_token["token"], ) There’s an API for that! @mariatta PyCon Colombia 2022

Slide 28

Slide 28 text

Google APIs There’s an API for that! @mariatta PyCon Colombia 2022

Slide 29

Slide 29 text

Google Slides API

Slide 30

Slide 30 text

Google APIs • Dev Docs: https://developers.google.com/ • OAuth 2.0 authentication • O ff icial Client Libraries: Go, Java, JavaScript, .NET, Node.js, Obj-C, PHP, Python, Ruby There’s an API for that! @mariatta PyCon Colombia 2022 > python3 -m pip install google-api-python-client

Slide 31

Slide 31 text

Google APIs from googleapiclient.discovery import build service = build("sheets", "v4", credentials=creds) result = ( service.spreadsheets() .values() .get(spreadsheetId=SPREADSHEET_ID, range=SHEET_RANGE) .execute() ) values = result.get("values", []) for row in values: print(row) API for reading rows from Google Sheets There’s an API for that! @mariatta PyCon Colombia 2022

Slide 32

Slide 32 text

Google APIs from googleapiclient.discovery import build service = build("slides", "v1", credentials=creds) requests = { "createSlide": { "objectId": "slide_page_1", "slideLayoutReference": {"predefinedLayout": "TITLE_AND_BODY"}, } } body = {"requests": requests} response = ( service.presentations() .batchUpdate(presentationId=PRESENTATION_ID, body=body) .execute() ) API for adding a slide on Google Slides There’s an API for that! @mariatta PyCon Colombia 2022

Slide 33

Slide 33 text

Google APIs requests = [{ "insertText": {"objectId": page_title["objectId"], "text": "Google APIs samples", }, }, { "insertText": {"objectId": page_body["objectId"], "text": "Visit the docs at https://developers.google.com/", }, }, ] request_body = {"requests": requests} response = ( service.presentations() .batchUpdate(presentationId=PRESENTATION_ID, body=request_body) .execute() ) API for adding texts to a page on Google Slides There’s an API for that! @mariatta PyCon Colombia 2022

Slide 34

Slide 34 text

Slack APIs There’s an API for that! @mariatta PyCon Colombia 2022

Slide 35

Slide 35 text

Slack APIs • Dev Docs: https://api.slack.com/ • O ff icial SDKs: Python, Node, and Java • Docs and Tutorials: https://slack.dev/python-slack-sdk/ There’s an API for that! @mariatta PyCon Colombia 2022 > python3 -m pip install slack_sdk

Slide 36

Slide 36 text

Slack APIs from slack_sdk import WebClient client = WebClient(token=token) response = client.chat_postMessage( channel="general", text="¡Hola, PyCon Colombia!" ) API for posting a message in a channel There’s an API for that! @mariatta PyCon Colombia 2022

Slide 37

Slide 37 text

Gitter APIs There’s an API for that! @mariatta PyCon Colombia 2022

Slide 38

Slide 38 text

Gitter APIs • Dev Docs: https://developer.gitter.im/ • Third Party API Wrappers: .NET, Java, Go, PHP, Python, Dart • Python wrapper: https://github.com/myusko/GitterPy There’s an API for that! @mariatta PyCon Colombia 2022 > python3 -m pip install gitterpy

Slide 39

Slide 39 text

Gitter APIs from gitterpy.client import GitterClient gitter = GitterClient(token) gitter.messages.send("my_gitterbot/Lobby", "¡Hola, PyCon Colombia!") API for posting a message in a channel There’s an API for that! @mariatta PyCon Colombia 2022

Slide 40

Slide 40 text

HackMD APIs There’s an API for that! @mariatta PyCon Colombia 2022 (Beta)

Slide 41

Slide 41 text

HackMD APIs • Dev Docs: https://hackmd.io/@hackmd-api/ • Authenticate using API key • No Python client library :( • Use requests or HTTPX • Maybe you should write one :) There’s an API for that! @mariatta PyCon Colombia 2022 (beta)

Slide 42

Slide 42 text

HackMD APIs API for reading a note (using httpx) There’s an API for that! @mariatta PyCon Colombia 2022 import httpx API_URL = "https://api.hackmd.io/v1" def get_hackmd_note(note_id): header = {"Authorization": f"Bearer {HACKMD_API_KEY}"} url = f"{API_URL}/notes/{note_id}" response = httpx.get(url, headers=header) return response.json()["content"] (beta)

Slide 43

Slide 43 text

Musixmatch APIs There’s an API for that! @mariatta PyCon Colombia 2022

Slide 44

Slide 44 text

Musixmatch APIs • Dev Docs: https://developer.musixmatch.com/ • Authenticate using API key • No o ff icial Python client library, but they have OpenAPI specs • Swagger SDK client: https://github.com/musixmatch/musixmatch-sdk • Third party Python wrapper: pymusixmatch There’s an API for that! @mariatta PyCon Colombia 2022 > python3 -m pip install pymusixmatch

Slide 45

Slide 45 text

Musixmatch APIs API for getting lyrics from a song and artist There’s an API for that! @mariatta PyCon Colombia 2022 from musixmatch import Musixmatch musixmatch = Musixmatch(API_KEY) def get_lyrics(song, artist): response = musixmatch.matcher_lyrics_get(song, artist) return response["message"]["body"]["lyrics"]["lyrics_body"] print(get_lyrics("I Want You", "Savage Garden"))

Slide 46

Slide 46 text

Integrate with multiple APIs There’s an API for that! @mariatta PyCon Colombia 2022

Slide 47

Slide 47 text

PyLadies Bot • Connects PyLadies GitHub repo to Slack • Shares events posted on GitHub to Slack channel • Repo: https://github.com/pyladies/pyladies-bot There’s an API for that! @mariatta PyCon Colombia 2022

Slide 48

Slide 48 text

HackMD <—> Discord • Post team meeting notes from HackMD to Discord There’s an API for that! @mariatta PyCon Colombia 2022 import discord import http client = discord.Client() @client.event async def on_ready(): channel = client.get_channel(id=channel_id) notes = get_hackmd_note(note_id) with open("meeting_notes.md", "wb") as notes_file: notes_file.write(notes.encode("utf - 8")) file = discord.File("meeting_notes.md") await channel.send( "Here's this week's meeting notes!", file=file) client.run(DISCORD_TOKEN)

Slide 49

Slide 49 text

Musixmatch <—> HackMD • Save your favourite song lyrics to HackMD There’s an API for that! @mariatta PyCon Colombia 2022 title = "I Want You" artist = "Savage Garden" lyrics = get_lyrics(title, artist) def create_hackmd_note(title, content): header = {"Authorization": f"Bearer {HACKMD_API_KEY}"} url = f"{API_URL}/notes" data = {"title": title, "content": content} httpx.post(url, json=data, headers=header) create_hackmd_note(f"{title} Lyrics by {artist}", lyrics)

Slide 50

Slide 50 text

Be respectful Be responsible There’s an API for that! @mariatta PyCon Colombia 2022 Don’t spam others with your bot Don’t abuse the data and the platform

Slide 51

Slide 51 text

Thank you! PyCon Colombia 2022 @mariatta There’s an API for that! @mariatta