我们经常发布文档更新,此页面的翻译可能仍在进行中。有关最新信息,请访问英文文档。如果此页面上的翻译有问题,请告诉我们

此版本的 GitHub Enterprise 已停止服务 2020-11-12. 即使针对重大安全问题,也不会发布补丁。 要获得更好的性能、改进的安全性和新功能,请升级到 GitHub Enterprise 的最新版本。 如需升级方面的帮助,请联系 GitHub Enterprise 支持

Using the GitHub API in your app

Learn how to set up your app to listen for events and use the Octokit library to perform REST API operations.

本文内容

简介

This guide will help you build a GitHub App and run it on a server. The app you build will add a label to all new issues opened in the repository where the app is installed.

This project will walk you through the following:

  • Programming your app to listen for events
  • Using the Octokit.rb library to do REST API operations

注:本指南演示了使用 Ruby 编程语言的应用程序开发过程。 但有很多Octokit 风格。 如果您喜欢 JavaScript,可以使用 ProbotNode.js 开发 GitHub 应用程序。

Once you've worked through the steps, you'll be ready to develop other kinds of integrations using the full suite of GitHub APIs.

基本要求

You may find it helpful to have a basic understanding of the following:

But you can follow along at any experience level. We'll link out to information you need along the way!

Before you begin, you'll need to do the following:

  1. Clone the Using the GitHub API in your app repository.

    $ git clone https://github.com/github-developer/using-the-github-api-in-your-app.git

    Inside the directory, you'll find a template_server.rb file with the template code you'll use in this quickstart and a server.rb file with the completed project code.

  2. Follow the steps in the Setting up your development environment quickstart to configure and run the template_server.rb app server. If you've previously completed a GitHub App quickstart other than Setting up your development environment, you should register a new GitHub App and start a new Smee channel to use with this quickstart.

    This quickstart includes the same template_server.rb code as the Setting up your development environment quickstart. Note: As you follow along with the Setting up your development environment quickstart, make sure to use the project files included in the Using the GitHub API in your app repository.

    See the Troubleshooting section if you are running into problems setting up your template GitHub App.

Building the app

Now that you're familiar with the template_server.rb code, you're going to create code that automatically adds the needs-response label to all issues opened in the repository where the app is installed.

The template_server.rb file contains app template code that has not yet been customized. In this file, you'll see some placeholder code for handling webhook events and some other code for initializing an Octokit.rb client.

Note: template_server.rb contains many code comments that complement this guide and explain additional technical details. You may find it helpful to read through the comments in that file now, before continuing with this section, to get an overview of how the code works.

The final customized code that you'll create by the end of this guide is provided in server.rb. Try waiting until the end to look at it, though!

These are the steps you'll complete to create your first GitHub App:

  1. Update app permissions
  2. Add event handling
  3. Create a new label
  4. Add label handling

步骤 1. Update app permissions

When you first registered your app, you accepted the default permissions, which means your app doesn't have access to most resources. For this example, your app will need permission to read issues and write labels.

To update your app's permissions:

  1. Select your app from the app settings page and click Permissions & Webhooks in the sidebar.
  2. In the "Permissions" section, find "Issues," and select Read & Write in the "Access" dropdown next to it. The description says this option grants access to both issues and labels, which is just what you need.
  3. In the "Subscribe to events" section, select Issues to subscribe to the event.
  4. 单击页面底部的 Save changes(保存更改)
  5. 如果您已经在您的帐户上安装了应用程序,请检查您的电子邮件并按照链接接受新的权限。 每次更改应用程序的权限或 web 挂钩时,安装应用程序的用户(包括您自己)都需要在更改生效之前接受新权限。 您也可以通过导航到安装页面并单击应用程序旁边的“Configure(配置)”来接受新的权限。 您将在页面顶部看到一个横幅,让您知道应用程序正在请求不同的权限。 单击“Details(详细信息)”,然后单击“Accept new permissions(接受新权限)”。

太好了! Your app has permission to do the tasks you want it to do. Now you can add the code to make it work.

步骤 2. Add event handling

The first thing your app needs to do is listen for new issues that are opened. Now that you've subscribed to the Issues event, you'll start receiving the issues webhook, which is triggered when certain issue-related actions occur. You can filter this event type for the specific action you want in your code.

GitHub sends webhook payloads as POST requests. Because you forwarded your Smee webhook payloads to http://localhost/event_handler:3000, your server will receive the POST request payloads in the post '/event_handler' route.

An empty post '/event_handler' route is already included in the template_server.rb file, which you downloaded in the prerequisites section. The empty route looks like this:

  post '/event_handler' do

    # # # # # # # # # # # #
    # ADD YOUR CODE HERE  #
    # # # # # # # # # # # #

    200 # success status
  end

Use this route to handle the issues event by adding the following code:

case request.env['HTTP_X_GITHUB_EVENT']
when 'issues'
  if @payload['action'] === 'opened'
    handle_issue_opened_event(@payload)
  end
end

Every event that GitHub sends includes a request header called HTTP_X_GITHUB_EVENT, which indicates the type of event in the POST request. Right now, you're only interested in issues event types. Each event has an additional action field that indicates the type of action that triggered the events. For issues, the action field can be assigned, unassigned, labeled, unlabeled, opened, edited, milestoned, demilestoned, closed, or reopened.

To test your event handler, try adding a temporary helper method. You'll update later when you Add label handling. For now, add the following code inside the helpers do section of the code. You can put the new method above or below any of the other helper methods. Order doesn't matter.

def handle_issue_opened_event(payload)
  logger.debug 'An issue was opened!'
end

This method receives a JSON-formatted event payload as an argument. This means you can parse the payload in the method and drill down to any specific data you need. You may find it helpful to inspect the full payload at some point: try changing logger.debug 'An issue was opened! to logger.debug payload. The payload structure you see should match what's shown in the issues webhook event docs.

太好了! It's time to test the changes.

注:您必须重新启动 Sinatra 服务器才可测试更改。 输入 Ctrl-C 停止服务器,然后再次运行 ruby template_server.rb。 如果您不想每次更改应用代码时都执行此操作,您可以查看重新加载

In your browser, visit the repository where you installed your app. Open a new issue in this repository. The issue can say anything you like. It's just for testing.

When you look back at your Terminal, you should see a message in the output that says, An issue was opened! Congrats! You've added an event handler to your app. 💪

步骤 3. Create a new label

Okay, your app can tell when issues are opened. Now you want it to add the label needs-response to any newly opened issue in a repository the app is installed in.

Before the label can be added anywhere, you'll need to create the custom label in your repository. You'll only need to do this one time. For the purposes of this guide, create the label manually on GitHub. In your repository, click Issues, then Labels, then click New label. Name the new label needs-response.

Tip: Wouldn't it be great if your app could create the label programmatically? It can! Try adding the code to do that on your own after you finish the steps in this guide.

Now that the label exists, you can program your app to use the REST API to add the label to any newly opened issue.

步骤 4. Add label handling

Congrats—you've made it to the final step: adding label handling to your app. For this task, you'll want to use the Octokit.rb Ruby library.

In the Octokit.rb docs, find the list of label methods. The method you'll want to use is add_labels_to_an_issue.

Back in template_server.rb, find the method you defined previously:

def handle_issue_opened_event(payload)
  logger.debug 'An issue was opened!'
end

The add_labels_to_an_issue docs show you'll need to pass three arguments to this method:

  • Repo (string in "owner/name" format)
  • Issue number (integer)
  • Labels (array)

You can parse the payload to get both the repo and the issue number. Since the label name will always be the same (needs-response), you can pass it as a hardcoded string in the labels array. Putting these pieces together, your updated method might look like this:

# When an issue is opened, add a label
def handle_issue_opened_event(payload)
  repo = payload['repository']['full_name']
  issue_number = payload['issue']['number']
  @installation_client.add_labels_to_an_issue(repo, issue_number, ['needs-response'])
end

Try opening a new issue in your test repository and see what happens! If nothing happens right away, try refreshing.

You won't see much in the Terminal, but you should see that a bot user has added a label to the issue.

Note: When GitHub Apps take actions via the API, such as adding labels, GitHub shows these actions as being performed by bot accounts. For more information, see "Machine vs. bot accounts."

If so, congrats! You've successfully built a working app! 🎉

You can see the final code in server.rb in the app template repository.

See "Next steps" for ideas about where you can go from here.

疑难解答

Here are a few common problems and some suggested solutions. If you run into any other trouble, you can ask for help or advice in the GitHub API 开发和支持论坛.

结论

After walking through this guide, you've learned the basic building blocks for developing GitHub Apps! To review, you:

  • Programmed your app to listen for events
  • Used the Octokit.rb library to do REST API operations

后续步骤

Here are some ideas for what you can do next:

  • Rewrite your app using GraphQL!
  • Rewrite your app in Node.js using Probot!
  • Have the app check whether the needs-response label already exists on the issue, and if not, add it.
  • When the bot successfully adds the label, show a message in the Terminal. (Hint: compare the needs-response label ID with the ID of the label in the payload as a condition for your message, so that the message only displays when the relevant label is added and not some other label.)
  • Add a landing page to your app and hook up a Sinatra route for it.
  • Move your code to a hosted server (like Heroku). Don't forget to update your app settings with the new domain.
  • Share your project or get advice in the GitHub API 开发和支持论坛