ApiClient Configurations Explained



Make Path Collection Variables Function Parameters


By default, path parameters become function parameters and collection variables in paths become instance variables of the ApiClient. This changes that and makes collection variables function parameters. Ex: "https://someurl.com/:pathVariable/{{someCllectionVariable}}". `pathVariable` will always be a function variable but this option gives you control over where `someCllectionVariable` goes.


False
:
private readonly string _somePathCollectionVariable; // Private variable
public async Task<List<Ticket>> GetTickets()
{
    return await _httpClient.GetFromJsonAsync<List<Ticket>>($"{_somePathCollectionVariable}/ticket.php");
}

True
:
// No private Variable
public async Task<Stream> GetTickets(string somePathCollectionVariable) // Now a function parameter
{
    return await _httpClient.GetFromJsonAsync<List<Ticket>>($"{somePathCollectionVariable}/ticket.php");
}

Use Cancellation Tokens


False
:
public async Task<Stream> GetTickets()
{
    var response = await _httpClient.GetAsync("{_someVariable}/ticket.php");
    return await response.Content.ReadAsStreamAsync();
}

True
:
public async Task<Stream> GetTickets(CancellationToken cancellationToken) // Now a function parameter
{
    var response = await _httpClient.GetAsync("{someVariable}/ticket.php", cancellationToken);
    return await response.Content.ReadAsStreamAsync(cancellationToken);
}

Attribute Library


You have two attribute libraries that you can choose from.

System.Text.Json
and
Newtonsoft.Json
. The attribute library you choose will have two affects. First, it will determine which
[JsonProperty]
Attribute to use on properties/fields of generated request and response classes. Secondly, it will determine which set of json extension methods your project is downloaded with. If you are unsure which to choose, choose
System.Text.Json
. Additionally, all
Newtonsoft.Json
extension methods have "Newtonsoft" in them.
GetAsJsonAsync
-
GetAsNewtonsoftJsonAsync
.


Multiple Response Handling


Enabling this setting is a great way to ensure that you are handling all possible responses from an api. When you enable this setting, the

StatusCode
of the response will be used to determine how the response is deserialized.


Handle
: The first option you have is whether you handle multiple responses at all. If you choose not to handle multiple response, then only the first success response (
StatusCode
>= 200 and < 300, preference to 200 if present) will be used in the generation process. All others will be discarded. This means that classes won't be generated for all other responses.


MultipleResponseHandling
: If you do decide to handle multiple responses by setting
Handle
to true, then you will need to decide what you want the return type to be when there are multiple responses. You can either return an
object
and allow the caller to determine the type... ew. Or you can use a discriminated union via the popular
OneOf
library. A discriminated union is a type that can be one of many types, but only ever ONE OF. In this case, the discriminated union will be one of the possible response types. This is the recommended option.



Xml Comments Types


You have full control over the type of

XmlCommentTypes
that are generated. Xml comments are generated from the description field of different parameters. Your options are ApiClient, QueryParameters, FormData, PathVariables, and Request. These are the locations of the generated xml comments.
  • ApiClient
    : Appear at the top of generated ApiClient, description comes from root item description.
  • QueryParameters
    : Each variable in the generated Parameters class will have an xml summary based on the description of the query parameters.
  • FormData
    : Same as before but for FormData.
  • PathVariables
    : An xml param tag will be generated on the ApiClient function for each path variable.
  • Request
    : An xml summary will be generated on the ApiClient function from the description of the postman request item.


Error Handling Strategy


None
: Request will be with no catch clause.


Thrown Exception
:
try
{
    // Request body
}
catch (HttpRequestException ex)
{
    // Error Handling Sinks
    throw;
}

Return Default
:
try
{
    // Request body
}
catch (HttpRequestException ex)
{
    // Error Handling Sinks
    return default;
}

Catch Exception Types


Each

CatchExceptionType
chosen will be caught. This setting only takes affect if
ErrorHandlingStrategy
is not
None


HttpRequestException
and
Exception
try
{
    // Request body
}
catch (HttpRequestException ex)
{
    // Error Handling Sinks
    throw;
}
catch (Exception ex)
{
    // Error Handling Sinks
    throw;
}

Error Handling Sinks


catch (// CatchExceptionType ex)
{
    _logger.LogError(ex); // Log Exception
    Console.WriteLine(ex); // Console Writeline
    Debug.WriteLine(ex); // Debug Writeline
    // Error Handling Strategy
}

Root Definition


  • Root
    : A root is any folder in a collection that has a request (including the root itself).
  • Host
    : The host part of a URL is the domain name or IP address that indicates where the resources are served from.
  • Authority
    : The authority component of a URL includes the authentication section, the host, and the port. In the URL
    "http://username:password@example.com:8080/path/to/file"
    -
    Authority
    :
    "username:password@example.com:8080"
    ,
    Host
    :
    "example.com"
    .
  • PerAuthorityPerFolder
    : An ApiClient will be created for each root, with a caveat being that if a root uses different authorities in it's requests, the requests will be regrouped into new roots based on authority.
    • Useful when the postman collection is well organized and you want your ApiClients to have seperation of concerns
  • PerAuthority
    : An ApiClient will be created for each authority disregarding the folders requests are in.
    • Useful when the you want a monolithic ApiClient.
  • Manual
    : Lets you decide how to requests get group.
    • Best of both worlds but requires you to manually group roots.

Class Deduding


  • Root
    : A class that's not a member of any other class
  • Non-Root
    : A class generated to be a member of another class.
  • Json Example
    : A key-value pair in json. In this section, it generally refers to a key-value pair where the value is an object. Denoted by "{}" in value. "person" : { }
  • Original Name
    : The value of the key in the json example.
  • Duplicate
    : A json example who's members match every single member by type and name on a previously processed json example. And the original and potential duplicate have the exact same amount of properties.
  • Semi-Duplicate
    : A json example who's members match every single member by type and name on a previously processed json example. And the original (already processed) has more properties than the potential duplicate.

RemoveDuplicateRoots
: You are given a couple of options to help reduce the number of classes generated. The first option lets you choose whether or not to remove duplicate ROOT classes. A root class is essentially one that is not a child of another class. These are your Request, Response, and Parameter classes. * Note: Root classes are subject to the same rules for deduping as non-root classes.


RemoveSemiDuplicateClasses
: The second option lets you choose whether to remove
Semi-Duplicate
, see definition above. Enabling this setting lets you dedupe these semi-duplicate classes. This is useful for json that has multiple examples of the same class but examples differ in name. For example, if you have Response that both have a Person object, but the json property names are different, this setting would let you dedupe the second example and put all unique properties in the first example. You are also able to adjust the sensitivity of this settings. The sensitivity is how many more properties the original can have than the duplicate. For example, if the original has 8 properties and the duplicate has 2 (all matching the original). Then
SameOriginalNameSensitivity
or
DifferentOriginalNameSensitivity
would have to be at least 6, depending on whether the names are the same or different.


OneTypePerJsonMemberName
: At the moment, this setting is only available for the Json2CSharpPlus tool found in other tools. Enabling this setting will enforce an additional rule during the dedupe process. Class deduping will work mostly the same but if 2 classes have the same name (in the json), the first one will be kept and all subsequent examples with just add their properties to the first. This is useful for json that has multiple examples of the same object under the same name but json examples have different amounts of properties. It is not useful when two json examples have the same name but represent different models. Then you would have one model to represent 2 objects. The default behaviour is create a second class with a number appended to the end if all the properties don't match.
Person2





Copyright © 2024 - Postman2CSharp All Rights Reserved
GitHub Repo Support me and the project