Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Understanding HTTP, Web APIs, and API Endpoints

 

Understanding HTTP, Web APIs, and API Endpoints

In the digital age, the seamless interaction between different software applications is paramount. This is where the concepts of HTTP, Web APIs, and API endpoints come into play, serving as the backbone of communication in the vast landscape of the internet and software applications. Let's delve into these concepts to understand their roles and how they work together to facilitate this communication.

How Service Protection API Limits are enforced

How Service Protection API Limits are enforced

 Reference

Service protection API limits are enforced based on three facets:

  • The number of requests sent by a user.
  • The combined execution time required to process requests sent by a user.
  • The number of concurrent requests sent by a user.

If the only limit was on the number of requests sent by a user, it would be possible to bypass it. The other facets were added to counter these attempts. For example:

  • You could send fewer requests by bundling them in batch operations.
    • The combined execution time limit will counter this.
  • Rather than sending requests individually in succession, you could send a large number of concurrent requests before service protection API limits are enforced.
    • The concurrent request limit will counter this.

Each web server available to your environment will enforce these limits independently. Most environments will have more than one web server. Trial environments are allocated only a single web server. The actual number of web servers that are available to your environment depends on multiple factors that are part of the managed service we provide. One of the factors is how many user licenses you have purchased.

The following table describes the default service protection API limits enforced per web server:




[Demo] Control your TESLA through Siri and Power Automate

[Demo] Control your TESLA through Siri and Power Automate

Imagine a scenario: in a freezing cold winter, you are heading to the parking lot for your Tesla car. You are holding a big box and have no hand to take out the phone then choose the commands from the menus to turn on the AC remotely, or open the rear trunk. So you just talk to your Apple watch and tell Siri to command the car easily and promptly. Is it an interesting experience you wanna try? If so, you may follow the below steps to finish your personal control application.

REST vs OData

REST vs OData

Understanding the Concept of REST APIs

Image Source: Astera Software

REST (REpresentational State Transfer) refers to a Software Architectural Style that defines the standards for exchanging information between two different systems via the HTTP Protocol. It is the most popular architecture for exchanging data on the World Wide Web.

REST defines 6 different principles for Web Services:

  • Uniform Interface: All components in a REST system must adhere to the same interface and rules so as to communicate with each other. 
  • Client-Server: REST separates Servers from Clients. The Servers store information, while the Clients retrieve information from the Servers. 
  • Stateless: All requests made via REST are stateless. They have all the necessary information needed by the Server to execute the request. 
  • Cacheable: In REST, both Clients and Servers can cache resources, which is good for reducing traffic and improving performance. 
  • Layered System: REST supports a Layered System Architecture. The Client may communicate with one Server, while the other Servers perform tasks such as Data Storage and Authentication. 
  • Code on Demand: REST requisitions may return executable code or logic when necessary (optional). 

Any API (Application Programming Interface) that follows the above principles is referred to as a REST API. In most cases, REST APIs use XML or JSON, but the REST Architecture doesn’t require anything specific as far as this is concerned. REST does not require any particular format, but it accepts any format that can be used in Content Negotiation

Understanding the Concept of OData

OData (Open Data Protocol) is a set of best practices for developing and using RESTful APIs. It helps you to focus on your Business Logic while creating RESTful APIs without the need to worry about various ways to define request and response Headers, HTTP Methods, Status Codes, Media Types, URL Conventions, Payload Formats, and more. 

Image Source: Progress Software

OData carries the following specifications:

  1. It must follow REST principles unless there is a clear reason why it should not.
  2. The OData services MUST have support for Atom encoding.
  3. OData services SHOULD have support for JSON encoding. 

REST is the most essential component technology of OData. OData 3.0 standards require OData users to follow REST principles. OData rests on HTML technology, which resolves the problem of being REST-based in a way. It supports two Protocols for Data Transfer, the XML-based Atom format and JSON. 

OData also has guidance for performing actions like defining reusable procedures, tracking changes, and sending many REST requests.  

It provides two models for Data Management which include:

  1. Entity Data Model (EDM): This is an abstract Data Model that OData users MUST use to describe the exposed data. 
  2. Service Model: It is made up of Static Resources and a set of Dynamic Resources. The work of the Static Resources is to provide a way of asking the Service about its Data Model, while the Dynamic Resources provide methods to manage the Data Model.

In the next section, we will be discussing OData vs REST APIs to know how the two compare in different core areas. 

OData vs REST APIs: What’s the Difference?

Let’s now discuss how OData and REST APIs compare to each other:

OData vs REST APIs: Function

REST Function

REST is an architecture that defines how to send messages between a Client and a Server via HTTP. It is a model that states that you can use HTTP and its verbs to perform CRUD Operations (Create, Read, Update, Delete) on the resources exposed by your Services. Thus, REST is more concerned about the architecture. 

OData Function

OData is a standard from Microsoft that relies on the REST Architecture to send specific types of messages over HTTP. It defines metadata in CSDL (Common Schema Definition Language) format to describe the Entity types supported by your Service and their Properties, Data types, and more. Thus, OData is more concerned about the content.

OData vs REST APIs: Principles

REST Principles

REST defines 6 principles, as has been listed above, to ensure the creation of efficient Web Services and REST APIs must follow these principles. These principles ensure the success of REST Projects. 

OData Principles

OData is built on top of the REST Framework, thus, it depends on REST principles. Note that even though OData recommends its users to follow REST principles every time, the requirement can be relaxed in the case of a good reason. A very basic, Compliant Service should be easy to build, with additional work necessary only to support additional capabilities. 

OData vs REST APIs: Best Use Case

REST API Best Use Case

REST is used when there is a need to interact with a Data Source, for example, to retrieve data for all Products. It is easier and faster to parse data using REST APIs. It uses URI to expose the Business Logic. 

The following operations are available on HTTP:

Image Source: Medium

OData Best Use Case

OData is best used to expose Services and APIs to Systems and Applications. It has facilities for extension to achieve the custom needs of the REST APIs. 

OData vs REST APIs: Data Transfer Format

REST Data Transfer Format

Data transfer format is an important factor to consider when comparing OData vs REST. REST supports the transfer of data in any format. Although most REST APIs use XML and JSON formats, REST is not specific in regard to this. 

OData Data Transfer Format

OData specifies that the data should be transferred in either JSON, XML, or Atom format. 

Those were the major differences between OData vs REST.  

Conclusion

This blog discussed fine differences across OData vs REST APIs. We also discussed concepts behind OData and REST APIs, their specifications and principles. 

For Businesses, extracting complex data from a diverse set of Data Sources such as REST APIs can be a challenging task. This is where Hevo saves the day by providing an efficient, reliable and fast ETL Service.

[DEMO] Synchronize Data from Business Central to Dynamics CE (Dataverse) through OData (Web API)

 Synchronize Data from Business Central to Dynamics CE (Dataverse) through OData (Web API)

Business Central Web Services: Page vs Codeunit vs Query Differences

 

Business Central Web Services

Business Central supports three types of web services: API, SOAP, and OData.

Creating HTML Web Resource To Show Image Attached In Notes Using Web API

 https://www.c-sharpcorner.com/article/creating-html-web-resource-to-show-image-attached-in-notes-using-web-api/


Some time back, I wrote a post for retrieving an image attached to notes using OData, as now for Dynamics 365 CE, we use Web API. So, I am going to share how we can do it using Web API.

Microsoft Dynamics CRM stores all the notes and attachments in annotation entities. Most out of the box entities used to have a relationship with this entity, but while creating our custom entity we can specifically select if we want to associate our custom entity with notes or not use the following option under Communication & Collaboration. Keep in mind once you enable this option, there is no way to disable this option, but if you are not sure, if you need notes or not at the time of your entity creation it's better to leave this option un-selected, so that you can select this option after sometime if required.

Note
The default size for notes attachment is 5 MB but if required, you can increase this limit to up to 32 MB.

We are going to implement following two steps,
  • Get entity image from notes
  • Create and deploy html web resource

Get entity image from notes

Similar to earlier versions we can upload the image to notes in Dynamics 365 CE.

Once image is attached to notes, we can retrieve it using Web API retrievemultiple request where we can query notes based on ObjectId field, we need to pass entity id field for objectid field in notes. We can using following code, in our html webresource,

  1. <html><head>  
  2. <script type="text/javascript">  
  3. //check if document is loaded or not  
  4. var imgControl = document.createElement("IMG");  
  5. //Check if documented loaded fully  
  6. document.onreadystatechange = function () {  
  7.    if (document.readyState == "complete") {  
  8.       getnotesImages();  
  9.    }  
  10. }  
  11.    
  12. //this function is used to get image from notes  
  13. function getnotesImages()  
  14. {  
  15.  //get regarding object id  
  16.    var regardingObjectId=window.parent.Xrm.Page.data.entity.getId().substring(1, 37);  
  17.    
  18.    //prepare URL  
  19.    var webapiURL=window.parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.2/annotations";   
  20.    
  21.    //prepare query  
  22.    var webapiQuery ="?$select=annotationid,documentbody,mimetype&$filter=_objectid_value eq "+regardingObjectId+" and  isdocument eq true and startswith(mimetype, 'image/')";  
  23.    
  24. //call image  
  25. var req = new XMLHttpRequest();  
  26. req.open("GET", webapiURL+webapiQuery, true);  
  27. req.setRequestHeader("OData-MaxVersion", "4.0");  
  28. req.setRequestHeader("OData-Version", "4.0");  
  29. req.setRequestHeader("Accept", "application/json");  
  30. req.setRequestHeader("Content-Type", "application/json; charset=utf-8");  
  31. req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=1");  
  32. req.onreadystatechange = function() {  
  33.     if (this.readyState === 4) {  
  34.         req.onreadystatechange = null;  
  35.         if (this.status === 200) {  
  36.             var results = JSON.parse(this.response);  
  37.            if(results.value.length>0) {  
  38.                 var annotationid = results.value[0]["annotationid"];  
  39.                 var documentbody = results.value[0]["documentbody"];  
  40.                 var mimetype = results.value[0]["mimetype"];  
  41.                 //set image  
  42.                 imgControl.src="data:" + mimetype + ";base64," + documentbody;  
  43.                 document.getElementById('imagediv').appendChild(imgControl);  
  44.             }  
  45.         } else {  
  46.             Xrm.Utility.alertDialog('Error while retrieving image details');  
  47.         }  
  48.     }  
  49. };  
  50. req.send();  
  51. }  
  52. </script>  
  53. <head><body style="zoom: 1; word-wrap: break-word;">  
  54.    
  55. <div style="width: 100px;" id="imagediv"></div>  
  56.    
  57. </body></html>  

Create and deploy html web resource

Now, we need to create an HTML web resource and use the above code under Text Editor.

After that, we can put this web resource to our required Entity Form and we should be able to see the first attached image in web resource after refreshing the page.

Next we will explain how to create a HTML web resource and use our JavaScript method to get and display the image. We need to implement the following two steps:

             · Create HTML page

             · Deploy HTML page and SDK.REST.js using web resource

Create HTML page

Create a HTML page using a HTML editor. Use the following code for the HTML page: 

  1. <html lang="en-us"><head>  
  2.  //Reference clientglobalcontest.js to get context information
  3.  <script src="../ClientGlobalContext.js.aspx"></script>
  4.  //add SDK.Rest.js reference
  5.  <script type="text/javascript" src="SDK.REST.js"></script>  
  6.  <script type="text/javascript">  
  7.   //check if document is loaded or not  
  8.    var imgControl = document.createElement("IMG");  
  9.    //Check if documented loaded fully  
  10.    document.onreadystatechange = function () {  
  11.    if (document.readyState == "complete") {  
  12.         getnotesImages();  
  13.    }  
  14.   }  
  15. //this function is used to get image from notes  
  16. function getnotesImages()  
  17. {  //get regarding object id  
  18.    var regardingObjectId=window.parent.Xrm.Page.data.entity.getId();  
  19.    //assign notes entity name  
  20.    var entitySchemaName="Annotation";  
  21.    var odataQuery = "?$top=1&$select=AnnotationId,DocumentBody,MimeType&" +  
  22.                     "$filter=ObjectId/Id eq guid'" + regardingObjectId +  
  23.                     "' and IsDocument eq true and startswith(MimeType,'image/') ";  
  24.    //call retrieveMultipleRecords method in SDK.REST javascript script library  
  25.    SDK.REST.retrieveMultipleRecords(entitySchemaName, odataQuery, getnotesImagesCallback, function (error) { alert(error.message); }, function(){});  
  26. }  
  27. //process callbanck result  
  28.  function getnotesImagesCallback(resultSet)  
  29.     {  
  30.         if (resultSet.length > 0) {  
  31.             var mimeType = resultSet[0].MimeType;  
  32.             var body = resultSet[0].DocumentBody;  
  33.             imgControl.src="data:" + mimeType + ";base64," + body;    
  34.             document.getElementById('imagediv').appendChild(imgControl);  
  35.             }  
  36.     }  
  37.  </script>  
  38. <meta charset="utf-8"></head><body style="zoom: 1;">  
  39. <div style="width: 100px;" id="imagediv"></div>   
  40. </body></html>  

Deploy HTML page and SDK.REST library using web resource

Use following procedure to deploy a HTML page and SDK.REST library in Microsoft CRM.

  •       Navigate to Settings -> Customization-> Customize the System from the top navigation bar
  •       Navigate to Components -> Web Resources-> New
  •       Fill in the details as in the following screen: 

  •        Click on the browse button and select your HTML web resource.
  •        Click on Save and then Publish
  •        Navigate to Components -> Web Resources-> New
  •        Fill in the details as in the following screen:

 

  •       Click on browse and select SDK.REST.js from Microsoft CRM SDK

Note: Please refer to my previous article for the SDK.REST.js location.

Now we can place our HTML web resource in the account entity form by navigating to Insert  -> Web Resource options. Save your changes and then publish the account entity form.
 
When you try to open your account record you should be able to see the attached images loaded into the HTML web resource.