Design Pattern for Creating an API URL

I am creating a class library that interacts with various third-party APIs. I used the facade template to simplify access to complex and confusing calls and the factory template to return the correct implementation. Now I'm trying to build one of the realities, but I do not think about elegant design.

The implementation I create requires the creation of a URL (which I do through URIBuilder). Then I need to "execute" the URL. Then I deserialize the Xml result into a class.

I plan to use HttpClient to call the api with the created URI, but not sure how to structure the class. The options I was thinking about are the following:

  • The base class of my implementation, so you can call it through base.InvokeURI(Uri myUri) .

  • The separation class, so it can be used by several implementations

I am also not sure where deserialization should exist.

+7
source share
2 answers

I think using an interface in this case is more suitable:

 public interface IURLInvoke { string InvokeURI(Uri myUri); } // some implementation public class YourURLInvoker: IURLInvoke { public string InvokeURI(Uri myUri) { // do something } } pubic class YourClass { public IURLInvoke Invoker {get; set;} public void InvokeURI(Uri myUri) { if(Invoker == null) return; string xml = Invoker.InvokeURI(Uri myUri); // put your code for deserialization here } } // here is an usage example: YourClass a = new YourClass(); // set an Invoker, choose a strategy to invoke url a.Invoker = new YourURLInvoker(); a.InvokeURI(url); 

This approach is also called Strategy Template.

+11
source

Pls sees dummy code using an adapter pattern and dependency injection. The idea is to create an interface and pass it

 public class Adapter{ public void processRequest(){ RequestProcessor processor = new RequestProcessor(); processor.processRequest(); } } public class RequestProcessor{ public void procesRequest(){ Irequest request = new HTTPRequest(); HTTPService service = new HTTPService(); // fetch the uri from builder class URI url = URIBUIlder(); string response = service.sendRequest(request,url); // now fetch type from just Type t = Serializer.searialize<T>(response); } } public Class Serializer{ public static T searialize<T>(string xml){ } } public interface IRequest{ public string sendRequest(uri url); } public class HTTPRequest:IRequest{ public string sendRequest(uri url){ // instantiate actual http request here and return response } } //This will act as controller public class HTTPService{ public string sendRequest(IRequest request,uri url) { return request.sendRequest(url); } } 
+1
source

All Articles