YouTube Channel Details API: Building and Testing a Python API Client

YouTube Channel Details API: Building and Testing a Python API Client

API provider: dataocean see on RapidAPI

Hi,

In our latest blog post, we shared how to create a Python package for interacting with The Better YouTube Channel Details API. If you missed that, I suggest checking it out first!

Here's where we are in our project journey:

🔹 First up: We're setting up the package and chatting with the API.
🔹 👉 We are here: Next: We'll dive into testing our creation.
🔹 And finally: We'll release it to the world at https://packagist.org/

Today's Focus:

  • Crafting a function to connect with the API endpoint.
  • Testing our implementation.

Let's dive in!

Ready to roll? Let’s go! 🎬

📡 Retrieving YouTube Channel Details

We previously set up a __get_request function to connect with the API and return JSON data. Today, we'll use this to obtain YouTube channel specifics.

API Documentation Insight: Endpoint: https://the-better-youtube-channel-details.p.rapidapi.com/GetChannelDetails Accepts a UrlOrUsername query parameter. Supports only the GET method.

Function Development:

   async def get_channel_details(self, urlOrUsername) -> any:
        response = await self.__get_request("/GetChannelDetails", urlencode({'urlOrUsername': urlOrUsername}))
        print(response)

In the previous post, when we were implementing __get_request, we explained why this function would take a query: dict parameter. Briefly, it's because urlencode, which is used for encoding special characters, returns them in the form of a dict.

👨‍💻 Testing Time!

It's crucial to validate our solution. Yes, ideally, tests come first, but sometimes they follow the coding phase. Our goal here is to ensure no errors and functional code.

Setting up the Test:

In tests/tests.py, add:

from src.youtube_channel_details_api_client_apiharbor.api_client import YouTubeChannelDetailsApiClient
print("it works!")

Our project stucture should like this

Run tests via command line: 

python -m tests.tests in \libs\youtube_channel_details_api directory.
Develop a basic test for API data retrieval:

api = YouTubeChannelDetailsApiClient("YOUR_RAPID_API_KEY")

async def test_get_channel_details():
  await api.get_channel_details('@MrBeast')

async def main():
  await test_get_channel_details()
  return None

asyncio.run(main())

Run the test and observe the results!

You shoud see JSON:

{'description': 'OK', 'status': 200, 'data': {'channel_url': 'https://www.youtube.com/channel/UCX6OQ3DkcsbYNE6H8uQQuVA', 'channel_name': 'MrBeast', 'channel_id': 'UCX6OQ3DkcsbYNE6H8uQQuVA', 'joined_date_text': 'Joined Feb 20, 2012', 'channel_country': 'United States', 'rss_url': 

🦾 We're the best! Everything works as it should, but we want to make our work easier in other projects. Therefore, we will do mapping from JSON to OBJECT.

🔄 JSON to Python Object Mapping

Next, we're installing the pydantic package to convert JSON data to Python objects

pip install pydantic.

Create src/schemas directory with a base model in base.py.

from pydantic import BaseModel
class BaseModelORM(BaseModel):
    class Config:
        from_attributes = True

Develop schemas/channel_details.py with the initial mapping for 'status' and 'description':

from .base import BaseModelORM

class ChannelDetails(BaseModelORM):
    status: int
    description: str

Update api_client.py to return a ChannelDetails object and modify the test to validate it.

async def get_channel_details(self, urlOrUsername) -> any:
        response = await self.__get_request("/GetChannelDetails", urlencode({'urlOrUsername': urlOrUsername}))
        return ChannelDetails.model_validate(response)

The final step is to modify the test_get_channel_details test.

async def test_get_channel_details():
    r = await api.get_channel_details('@MrBeast')
    assert r.status == 200

Run python -m tests.tests and... nothing appears. And that is great! Because no error is thrown.

🤖 Automating JSON Schema Generation

Instead of manual mapping, use https://jsontopydantic.com/ for automatic schema creation. You just need to input your JSON, and the tool will generate the schema for you.

📝 In Summary

Today, we:

  • Crafted and tested a function to fetch YouTube channel details.
  • Implemented JSON to Python object mapping.
  • Prepared the package for Packagist publication.

Thanks for joining. Stay tuned for more updates. 🚀