Search code examples
c#apijson.netdynamics-crmmicrosoft-dynamics

Dynamics CRM C# Plugin - First time with API


While I've been developing in Dynamics for awhile, I have never had to do an external call to an API before.

I'm not sure where to start. Any help in pointing me in the right direction would be very helpful.

The Api in question is located here: http://apidocs.assess.com/

There are examples within there that show what needs to get passed to the url (https://app.fasttestweb.com/FastTest/api/swagger.json) But in all honesty, this is my first attempt at this and I'm overwhelmed with the information I've been finding, and having trouble parsing through what needs to be done for this.

Step 1, of course is to generate an auth token from the site. This needs to be passed in this formation (I assume that is JSON). But I'm having trouble figuring out how to even do that part, or what the code should even look like. If anyone has an example of something they've done, or can point me to a link/video that walks through this, that would be awesome.

Note, I do have Newtonsoft.Json installed in Visual Studio, but I'm having trouble finding good examples on how to actually pass the information back and forth. Thank you in advance.


Solution

  • How to call an API in rest is a really common practice as a developer since this is common practice to expose data, i highly recommend that you read up on the subject, there are alot of good resources out there, this site is one and youtube is another, did a quick search and found alot about it: https://www.youtube.com/results?search_query=intro+to+rest+c%23

    To the problem at hand: The swagger documentation tells you all you need to know to call the service your after, Take the auth service for example, first of we need to know which method the service uses, in this case it is post. Now we need to know which address we can call the service. Specified in the docs as: https://app.fasttestweb.com/FastTest/api/auth/simple What are we sending:

    {
      "username": "string",
      "pwd": "string",
      "apiKey": "string",
      "timeSent": 0,
      "tokenTTL": 0
    }
    

    if you switch to model you can see the description of the parameters. You can even test this out directly in the page by editing the editable box with the values you were given and pressing "try it out!" in the bottom of the endpoint specification.

    What response are we getting:

    {
      "apiToken": "string",
      "timeGenerated": 0,
      "ttl": 0
    }
    

    To call it, there are many ways to do this, i like to make separate objects/dto's of what im sending and recieving and then serialize/deserialize them from and to that object. Since you already have json.net here is how you do serialize.

    You can specify the specific json names so it matches with the schema with an attribute or define a strategy.

    When you get the json back from the service you will have to deserialize it.

    So your body obj would look like this for example

     public class AuthBody
        {
            [JsonProperty("username")]
            public string UserName { get; set; }
    
            [JsonProperty("pwd")]
            public string Password { get; set; }
    
            [JsonProperty("apiKey")]
            public string ApiKey { get; set; }
    
            [JsonProperty("timeSent")]
            public int TimeSent { get; set; }
    
            [JsonProperty("tokenTTL")]
            public int TokenTimeToLive { get; set; }
        }
    

    Just setup the response in similar fashion. I like to use a lib called RestSharp to call rest services, its available on nuget. Here is a very basic code example (not tested):

    var body = new AuthBody()
                {
                    UserName = "value",
                    Password = "value",
                    ApiKey = "value",
                    TimeSent = 123,
                    TokenTimeToLive = 10000
                };
                var json = JsonConvert.SerializeObject(body);
    
                var client = new RestClient("https://app.fasttestweb.com/FastTest/api");
    
                var request = new RestRequest("auth/simple", Method.POST, DataFormat.Json);
                request.AddParameter("application/json", json, ParameterType.RequestBody);
    
                var jsonResponse = client.Execute(request);
                AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(jsonResponse.Content);
    

    You can also set the default serializer of restsharp to json.net if you want, then you can set the body with addJsonBody instead of the parameter and you dont have to serialize your object yourself, more info is available on RestSharp. if you dont want to use RestSharp, the normal client is called HttpClient instead of RestClient, if you want to google it.

    Hope it helps.