Upgrade to Pro — share decks privately, control downloads, hide ads and more …

There's an API for that!

There's an API for that!

PyCon Colombia Keynote

Mariatta

July 09, 2022

Transcript

51 slides
  1. 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
  2. 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
  3. What even is a bot? There’s an API for that!

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

    that! @mariatta PyCon Colombia 2022
  5. • 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
  6. • 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
  7. There’s an API for that! @mariatta Third Party API Your

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

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

    Party Webhooks API calls a.k.a bot PyCon Colombia 2022
  10. 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
  11. 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
  12. 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"]
  13. 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
  14. 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
  15. There’s an API for that! There’s an API for that!

    @mariatta Don’t Scrape PyCon Colombia 2022
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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)
  28. 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)
  29. 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
  30. 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"))
  31. 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
  32. 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)
  33. 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)
  34. 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

More Decks by Mariatta

Other Decks in Programming