Let’s talk about the best practices to use when consuming a third-party API — or even for working with your own!

Grab an official library

If you’re lucky, there will be an official client library available as a Nuget package for the API you’re working with. If there is, this is usually the best route to go since it will save you a lot of work. You just install the package and you’re good to go. You keep track of any updates to the library through Nuget.

Most really popular APIs do have an official .NET library, but not always. Sometimes you’ll get an API that isn’t targeting .NET developers, or they’re in competition with Microsoft, or something of that nature, and then it may be difficult to find .NET support directly. It all depends on the community of developers out there.

Don’t grab an unofficial library

If there is not an official client library, be very cautious about pulling some random library that says it’s for the API you want to work with. These are often experiments, tutorial projects, unfinished, or unsupported. You may be tempted, thinking it’ll save you time in using something someone else started, but in the end you run a risk of wasting time unraveling how it works, and finding what problems they didn’t solve.

You’re an awesome programmer. You should write your own API client library!

Writing your own API client gives you the benefit of knowing the code, and only including the parts of the API you’re actually interested in or plan to use. When there is no official library, the time you spend writing your own code is usually a good investment.

Steps for creating an API client

Pull up the third-party API documentation and let’s get started!

DTO classes

I always start by mapping the parts of the API I need to local Data Transfer Object classes. DTOs are used as containers for holding data and passing it along to other areas of the application. DTO classes do not contain any logic, just the properties representing the data. For example:

public class ExampleDTO
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public string DisplayName { get; set; }
}

Create classes with properties that match the properties of the objects listed in the API documentation. What you’re doing here is modeling the external API into strongly typed objects that you can use in your own local code.

One thing to note, however, is that APIs almost exclusively return JSON. JSON property naming conventions differ from C## in that they are usually camelcase. The property “ExampleProperty” in C## will probably be represented as “exampleProperty” in JSON. That’s even if the API authors follow conventions. You may find that they use underscores like “example_property”.

#api #rest-api-client #dotnet #c-sharp-programming

Best practices when consuming an API through C# and .NET
6.05 GEEK