Share
Embed
Transcript
51 slides
-
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 -
Bots of Python the-knights-who-say-ni bedevere-bot miss-islington blurb-it There’s an API
for that! @mariatta PyCon Colombia 2022 -
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 -
What even is a bot? There’s an API for that!
@mariatta PyCon Colombia 2022 -
Bot == ? There’s an API for that! @mariatta PyCon
Colombia 2022 -
Bot == Web App There’s an API for that! @mariatta
PyCon Colombia 2022 -
Bot == Web App == Automation There’s an API for
that! @mariatta PyCon Colombia 2022 -
• 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 -
• 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 -
There’s an API for that! @mariatta Third Party API Your
Web App The internet PyCon Colombia 2022 -
There’s an API for that! @mariatta Third Party API calls
Your Web App PyCon Colombia 2022 -
There’s an API for that! @mariatta Your Web App Third
Party Webhooks (Incoming API calls) PyCon Colombia 2022 -
There’s an API for that! @mariatta Your Web App Third
Party Webhooks API calls a.k.a bot PyCon Colombia 2022 -
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 -
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 -
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"] -
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 -
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 -
There’s an API for that! There’s an API for that!
@mariatta Don’t Scrape PyCon Colombia 2022 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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) -
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) -
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 -
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")) -
Integrate with multiple APIs There’s an API for that! @mariatta
PyCon Colombia 2022 -
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 -
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) -
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) -
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 -
Thank you! PyCon Colombia 2022 @mariatta There’s an API for
that! @mariatta