Invoking HTTP REST endpoints with one line of C# code

I have just created a small addition to Magic, which is the ability to invoke HTTP REST endpoints, with a single line of C# code. The thing relies upon intelligent use of generics, automatically transforming your DTO objects to JSON as you invoke REST endpoints. In addition, the class also intelligently looks to see if what you supply it as a generic argument is a Stream, and allows you to also supply a delegate taking a Stream. This allows you to download and upload huge files, without exhausting your client’s memory resources. This reduces your HTTP REST invocations to a single line of C# code.

To understand how to use it, take a look at my unit tests for the class. Notice, normally you’d simply inject a constructor argument of type IHttpClient to your classes, and retrieve an instance to the HttpClient through dependency injection – And not directly instantiate it as I do in my unit tests. To see the class, and how it is implemented, you can check out its GitHub repository. The class is “super DRY”, implying it doesn’t contain any repeating code, allowing you to easily change it according to your needs. The class also allows you to return anything that’s implementing IConvertible, allowing you to use it in combination with endpoints returning integer values, string, etc – Which is useful for endpoint returning simple atomic values, and not complex JSON types.

Internally the class consumes HttpClient, and hence is also extremely “async in nature”, allowing for invoking HTTP REST API endpoints in an extremely optimised way, utilising your client’s resources in the best possible way.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.