How can I create a custom Moodle plugin that integrates with an external API?

I am developing a custom Moodle plugin that needs to fetch data from an external API and display it in a course module. My goal is to:

  1. Authenticate with the external API using OAuth2.
  2. Fetch specific data (e.g., user progress, grades, or content).
  3. Display this data in a custom Moodle block or activity module.

I’ve reviewed the Moodle Developer Documentation, but I’m unclear on:

  • How to structure the plugin for external API integration.
  • Where to implement API calls (e.g., lib.php, custom classes, or AJAX).
  • The best practices for securely storing and refreshing OAuth2 tokens.

Here’s what I’ve tried so far:

  • I’ve created the basic plugin structure using the Moodle plugin skeleton generator.
  • I’ve registered an external service for the API under Site Administration > Plugins > Web Services.

However, I’m struggling with how to handle authentication and integrate API data seamlessly into Moodle.

What are the best practices for implementing such functionality in Moodle plugins? Are there any existing examples or patterns I should follow?