In this article, we embark on an exciting journey to create a C# API client that interfaces with the Netflix API. It's important to note that Netflix doesn't offer an official API, so we'll be utilizing a set from RapidAPI. Among the options, DataOcean's Netflix API emerged as my top pick for several compelling reasons:
- Its novelty often translates to better features.
- The simplicity is key — with just 7 endpoints, it covers nearly all desired functionalities.
- Affordability is a great plus.
- Rapid performance seals the deal.
With these criteria in mind, let's dive in!
First things first, we'll adhere to a naming convention for clarity and organization:
Our project's initial layout looks fantastic and promising. The guiding principle here is "less code, more efficiency." At this point, our codebase is a clean slate, perfectly set up for our next steps 😉.
Now, let's break this perfection by adding the code 😉.
To query an endpoint on RapidApi, two additional header values are crucial:
You can find these in the Code Snippets section on the API's webpage - https://rapidapi.com/dataocean/api/netflix99
NetflixApiClient constructor should definitely accept a
rapidApiKey for use in requests. Let's consider if we need anything else. For sure something that communicates over
http/s. In C#, there are several methods for this, we can use:
We wouldn't want to restrict the user to a specific method, so our constructor will accept an
IWebClient interface. This way, users can choose their preferred implementation. A logger would also be handy to know what's happening during API usage. We'll follow a similar approach as before, providing a custom
ILogger interface, compelling the user to implement it.
Here, we aim for simplicity. Our logger should have two methods: one for informational messages and another for handling exceptions.
Returning to our
NetflixApiClient.cs, let's implement what we've outlined so far.
With the current implementation, we meet all our initial objectives:
- Flexibility in passing any
- Freedom from being tied to any particular logger implementation.
- The constructor accepts our
Let's move on to the more exciting parts! 🔥
The Netflix API we're working with provides seven endpoints:
- Search titles - title search (surprise! 😃)
- Title lists - returns titles according to defined parameters
- Title details - returns title details based on the ID from Search title
- Similar titles - returns similar titles also with ID received from Search
- Title credits - returns a list of actors and people working on the title
- Title media - returns a listing of images, posters, videos
- Person details - retrieves information about a given actor or team member. Accepts ID received from Title credits.
As our first method to implement, let's choose
Search title, as the other endpoints require IDs returned by this method.
Search titles endpoint accepts several parameters, including:
query- searched phrase
order- sorting of results
title type- option to return results only for movies or TV shows or all (All)
token- for the next page of results
Let's make a sample request and examine the response from
- Status information is provided (e.g.,
status: 200for success).
- Relevant data is assigned to data.
- Separate pagination property includes a prepared URL for the next page and
- The total number of results and pages, as well as the number of titles returned per response, are provided.
Inspecting a single title element reveals:
This gives us a good understanding of
Search titles. Let's get to the implementation.
We'll create a new class to map the JSON response from the API to a
SearchTitlesResponse object. In today's world, manual JSON mapping is a thing of the past. Tools like json2csharp make this task a breeze. Let's use it to generate our response class.
Copy the entire JSON and then paste it into json2csharp and click on Convert.
A beautiful response class has been generated for us. We will further enhance it by adding nullable **fields and using **PascalCase
Now it's perfect! Just take a look at the response.
Our class is ready, let's integrate it into our project.
As we see something is missing. To use
JsonProperty, we need to install
And by the way, we will implement a static method that will convert (deserialize) pure JSON in text form into a
The structure of our project currently looks like:
Great! Now that we can map the JSON to
SearchTitlesResponse, it's time to fetch the JSON from the Netflix API.
Let's go to
NetflixApiClient and implement the method.
Remember, Search titles can accept numerous parameters, so let's get those implemented.
Quite a long process. Well, let's move on…
However let's STOP here! Instead of building a raw URL string in the client, let's create a separate
SearchTitlesRequest class that handles query parameters and returns a formatted URL for communication with the Netflix API.
Let's add another method that will return joined parameters for us.
Yes. In this way, I avoid writing long strings, I prefer to put each parameter separately into an array and then join them with &. It looks better, right? 😃 Let's look at the full implementation of SearchTitles.
We can call the
SearchTitles method by passing a
SearchTitlesRequest object or using ordinary parameters.
Now the handling of the Search title endpoint looks awesome!🔥
Before testing our Search method, let's modify one assumption. We gave users the option to implement their own
http/s communication and logger. But not everyone might want to do this. Some might prefer a straightforward way to fetch data without extra implementation. Let's accommodate this preference.
We add a new
DefaultWebClient class in
HttpClient for requests.
Similarly, we add a
DefaultLogger class in the same namespace, providing the simplest implementation of the
The default logger will simply display messages in the Console. Users can always implement their own logger for different outputs, like file logging or database storage.
Since we're not enforcing the use of custom
ILogger, we need to adjust the constructors of
With these new constructors, users now have the choice to use the defaults or implement their own!
To test the Netflix API, all we need is the
X-RapidAPI-Key and some code.
Let's also test fetching subsequent pages of results using the provided URL.
We need to modify
NetflixApiClient to add a simple variant of the
SearchTitles method, named
SearchTitlesByUrl, accepting the
Let's modify the test code a bit more in the console application. The modification concerns querying the next page (we have it at hand in
NextPageUrl). The querying loop will operate until Data is not empty. Simple and effective 👌
Running the code with modification from above…
…gives us correct results. We can observe this through the titles come from the next (second) page. Brilliant!
What's next? I believe it's time to tackle the
Title details endpoint.
I believe it's time to tackle the Title details endpoint.
- Visit the Netflix API page on RapidApi.
- Choose the
Title detailsendpoint and execute it.
- Copy the JSON result.
- Use json2csharp to generate the
- Remember to set Property Settings as follow
- We paste the JSON and click 'Convert' button.
- We create a new class in Responses:
TitleDetailsResponseand implement the Create method (as before).
- Let's see how it looks now
- JSON to response object mapping seems to be ready!
Now let's implement the API request method in our
Yes, this simple code is sufficient. This time, we won't implement the creation of the API URL in the response class (
TitleDetailsResponse), as the needed URL is very simple. But of course, following good practices, we should do so… Anyways! We need the test code to check if getting
Today, we nearly completed an entire library for interacting with the Netflix API.
- We added default classes for
http/scommunication with API and a console-based logger.
- By using Dependency Injection, we provided the option for users to create their own versions of an HTTP client and logger through our interfaces
- Responses are neatly mapped from raw JSON text to Response objects with the help of the json2csharp.com
- And the most important result of the project: we are able to very easily retrieve data from the API using our client class -
Everything went smoothly and easily… perhaps even too easily 😉
You can check out the entire project on GitHub:
Next time, we'll build a sample project using this library… OR! we'll write another article expanding the library with some additional interesting features. We'll see.
Thanks for your time ❤️ See you!
Follow me to not miss out on future updates! 🔥