How to use an API
CONCEPTS
In order to follow the instruction for using an API in APIM it would help to understand a few terms.
Azure Active Directory: Microsoft's cloud-based identity and access management service, which helps your employees sign in and access resources. Primarily for internal resources, such as apps on your corporate network and intranet, along with any cloud apps developed by your team.
Application Registration: Application registration provides you with OAuth credentials required for user authorization. You will use the form to register your application.
OAuth: A flexible, drop-in solution to add authentication and authorization services to your applications. Your team and organization can avoid the cost, time, and risk that comes with building your own solution to authenticate and authorize users.
RESTful API: A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology because REST leverages less bandwidth, making it more suitable for internet usage.
REST Client: A method or a tool to invoke a REST service API that is exposed for communication by any system or service provider.
Prerequisites
In order to successfully use your API in the Azure APIM instance set up by DECO you will need the following items:
Access to Azure Active Directory to create application registrations.
Postman, Insomnia or any other REST client.
PERMISSION SET UP
Create an Application Registration
All calls done through APIM to a particular API will require that a Application Registration is created. This will allow Midmark to control permission for given application base on their need. In order to create a Application Registration in Azure follow the directions below.
Navigate to Azure Active Directory .
While in Azure Active Directory, on the left side of the screen scroll down until you see App Registrations. Click on this menu option.
At the top of the new screen click the option New registration.
In the entry screen enter a display name for your new Application Registration in the below format. The display name cannot contain any whitespace. Also Application Registrations should not be reused between different applications and environments.
<team name>-<application name>-<environment>
Team Name: This should be the unique name that identifies your team at midmark.
Application Name: The name of the application that will require access to a particular api.
Environment: This will either be dev, test or prod depending on the environment a particular application is running in.
After having typed in the display name select the radio options Single Tenant underneath text "Who can use this application or access this API?"
Click the blue Register button at the bottom of the screen.
Now that the creation of the Application Registration is complete note down the Application (client) ID found on the Overview page.
Creating Client Secret
In order for a particular request to prove it is on behalf of your Application Registration we will also need to create an associated Client Secret.
Navigate to the Application Registration you created in the step above in Azure Active Directory .
On the left side of the screen scroll down until you see the menu option Certificates & Secrets.
In this new screen scroll down until you see the Client Secrets section.
Click the button labeled New client secret.
In the menu add a description that is relevant to the application that will be using this Client Secret.
Also select one of the radio button that follows the standard of your team or leave the default option In 1 year selected.
Click the Add button to create your Client Secret.
It is very important not to navigate or refresh your browser window after having created your Client Secret. You will only get the secret value ONCE during this process.
After being pulled back to the original screen, copy the Client Secret value. Ensure you do not lose this value before completing the rest of these steps.
If you do lose the value of your Client Secret simply delete the older value and follow the "Creating a Client Secret" steps again.
Requesting API Permissions
Now that we have an Application Registration and the associate key the Application Registration needs to be assigned to the correct groups for permission.
Send an email to the DL "DECO-DevOps@midmark.com". Your email should be formatted as below.
SUBJECT:
Request for access to <API Name>
BODY: I am requesting access to the API '<API Name>' controlled by your team. Below are the details of my Application Registration.
App Registration Name: <Application Registration Name>
Client ID: <Client ID>
Implementation Deadlines: <Date>
Usage Details: <Usage Details>
API Name: The name of the API you wish to integrate with.
Application Registration Name: The display name of the Application Registration you created in the earlier steps.
Client ID: This will be the GUID you noted in the earlier steps after creating your Application Registration.
Usage Details: In order for you to get the permissions that best match your usage of an API, please give a quick explanation on how your integration with this API will work. Note that a DECO representative will most likely open up a dialog to best determine your needs.
After having sent an email to the DECO team and your Application Registration is assigned to the correct groups, skip to the section SENDING A REQUEST.
Associating an Application Registration to Permission Groups
The steps below are for the team who will be adding your Application Registration to the correct permission groups. The below direction will be using the Users API as an example.
Navigate to Azure Active Directory .
While in Azure Active Directory, on the left side of the screen scroll down until you see Groups. Click on this menu option.
In the All Groups menu, search for the DECO-UsersAPI.
There are multiple options to choose from when looking at the permissions groups.
Prod: A group with this text as part of its name is for production environment.
NonProd: A group with this text as part of its name is for the development and test environment.
Admin: A group with this text as part of its name allows an caller to use any method on a particular REST service.
Reader: A group with this text as part of its name allows an caller to use only use GET methods on a particular REST service.
After having selected the correct group based on the news of a particular team, click on that group.
Scroll down until you see the Members menu options on the left side of the screen.
At the top of the screen click the Add Members option.
In the new window that pops up to the left type the name of the Application Registration, select it and click the Select button.
SENDING A REQUEST
Below will be an explanation of actually sending a request to an API in APIM. All examples and directions will be using the REST Client software Insomnia and the Users API.
Set up
After having downloaded and installed Insomnia , open up the application.
In the Insomia window that opens, go to the left side of the screen and right click then select New Request.
Leave the default options and click the Create button.
In the top URL text box copy the following text:
https://private-dev.api.midmark.com/Users/api/users/9c2c0c59-757a-4f3b-a526-7a4d5f283030?api-version=0
Below the URL textbox is a menu tab labeled Auth. Click on the down arror in the tab and select the OAuth2 option.
In the new window that opens set each options as follows.
Grant Type:
Client Credentials
Access Token URL:
https://login.microsoftonline.com/3c2a020d-f343-4ca1-b6ef-91768380352f/oauth2/token
The GUID found in this setting is the tenant id for Midmark in Azure.
Client Id: This is the client id of the Application Registration you made in the Create an Application Registration section above.
Client Secret: This is the client secret of the Application Registration you made in the Creating Client Secret section above.
Enabled: This is checked.
Click on the Advanced Options label and fill out the options as follows:
Scope: This is empty.
Credentials:
As Basic Auth Header (default)
Header Prefix:
Bearer
Audience: This is empty.
Resource:
c7e19a6c-fbcf-469c-9913-fb0b41616174
The GUID found in this setting is the object id for Application Registration used by the Users API in Azure.
Making the Request
After having input all of the values above, click the Fetch Token button at the bottom of the screen.
Now, finally, click the Send bottom at the top of the screen. You will get a 200 status code back and some user data.
USING AUTOREST
Introduction
You can use AutoRest to generate an api client for each published api.
HttpClient Project Conventions
ClientName: {api-name}ApiClient
ProjectName: Midmark.{Team}.{Project}.{ClientName}
Path: src/{ProjectName}
Example:
ClientName: CustomersApiClient
ProjectName: Midmark.DECOPlatform.E2ETests.CustomersApiClient
Path: src/Midmark.DECOPlatform.E2ETests.CustomersApiClient
Prereq
Node.js
The swagger file downloaded from the API details page.
(OpenAPI 3.0 definition required)
Create a new project for the api client to be generated and add the nuget
Microsoft.Rest.ClientRuntime
Install
npm install -g autorest
Create a config.yaml file
There is a config.yaml
file that the autorest command uses. The reason for this is due to the way references are written in the swagger file that was generated were not "proper" and autorest does not like it during code generation. The configuration has a directive that makes the changes needed to get autorest to generate the code.
# directives can modify the swagger on the fly
directive:
- from: swagger-document
where: $.components..properties[?(@.allOf.length === 1 )]
reason: unroll properties that have allOf declarations that are alone
# check to see if the property found at $
# - which we know to be an allOf with a single item
# - has only one property
transform: 'return (Object.keys($).length === 1 ) ? $.allOf[0] : $'
Create a powershell script to generate ApiClients
Create a new powershell script file and name it after the target api. Something like Generate<
ClientName>.ps1
. In this example if it was the customers api as the target api the name of the file should be GenerateCustomersApiClient.ps1
. Put this file in the root of your solution.
Copy and paste the following code into the file:
param(
[string][Parameter(Mandatory=$true)]$SwaggerFilePath
[string][Parameter(Mandatory=$true)]$OutPutFilePath
[string][Parameter(Mandatory=$true)]$Namespace
[string][Parameter(Mandatory=$true)]$ClientName
)
Write-Output $InputFilePath
# Clear the previously generated code.
Remove-Item "$OutPutFilePath/Generated" -Force -Recurse -ErrorAction Ignore
# Generate a C# client from the Swagger definition and
# override the namespace and the client name.
autorest --input-file=$SwaggerFilePath `
--output-folder="$OutPutFilePath/Generated" `
--namespace=$Namespace `
--override-client-name=$ClientName `
--v3 `
--csharp `
--verbose `
--generate-empty-classes `
--add-credentials
Generate an api client
run the Generate<
ClientName>.ps1
script with the following parameters:
SwaggerFilePath :
The path to the swagger document.
OutPutFilePath :
The path to the output directory.
From example:
Path
Namespace :
The namespace to decorate the class.
From example: ProjectName
ClientName :
The name of the class generated.
From example: ClientName
Modify generated class
You will have to modify the generated class to include api-version={targetVersion}
for each method that calls an api endpoint.
Example:
After generating files for the UsersApiClient navigate the project folder and open the "Generated" folder. You will see a Users.cs file. That file will have a method for each API endpoint. For each method you will need to modify the calling url to include the api-version parameter.
// Added this line due to APIM work around.
_url = $"{_url}?api-version=0";
If you do not do this you will receive 404 errors.