Implement API Management - 2023
Implement API Management - 2023
Implement API Management - 2023
To use API Management, administrators create APIs. Each API consists of one or more operations, and each API can be
added to one or more products. To use an API, developers subscribe to a product that contains that API, and then they
can call the API's operation, subject to any usage policies that may be in effect.
1
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
over URL mapping, query and path parameters, request and response content, and operation response caching. Rate limit,
quotas, and IP restriction policies can also be implemented at the API or individual operation level.
Products:
Products are how APIs are provided to developers.
Products in API Management have one or more APIs, and are configured with a title, description, and terms of use.
Products can be Open or Protected. Protected products must be subscribed to before they can be used, while open
products can be used without a subscription. Subscription approval is configured at the product level and can either
require administrator approval, or be auto-approved.
When a product is ready for use by developers it can be published.
Groups are used to manage the visibility of products to developers.
Groups:
API Management has the following immutable system groups.
Administrators - Azure subscription administrators are members of this group. Administrators manage API
Management service instances, creating the APIs, operations, and products that are used by developers.
Developers - Authenticated developer portal users fall into this group. Developers are the customers that build
applications using your APIs. Developers are granted access to the developer portal and build applications that call the
operations of an API.
Guests - Unauthenticated developer portal users, such as prospective customers visiting the developer portal of an
API Management instance fall into this group. They can be granted certain read-only access, such as the ability to view
APIs but not call them.
Note: In addition to these system groups, administrators can create custom groups or leverage external groups in
associated Azure Active Directory tenants.
Policies:
Policies are a powerful capability of API Management that allow the publisher to change the behavior of the API
through configuration.
Policies are a collection of statements that are executed sequentially on the request or response of an API.
Popular statements include format conversion from XML to JSON and call rate limiting to restrict the amount of
incoming calls from a developer, and many other policies are available.
Developers
Developers represent the user accounts in an API Management service instance.
2
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
Developers can be created or invited to join by administrators, or they can sign up from the Developer portal.
Each developer is a member of one or more groups, and can be subscribe to the products that grant visibility to those
groups.
When developers subscribe to a product they are granted the primary and secondary key for the product. This key is
used when making calls into the product's APIs.
Developer portal
The developer portal is where developers can learn about your APIs, view and call operations, and subscribe to
products.
You can customize the look and feel of your developer portal by adding custom content, customizing styles, and
adding your branding.
3
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
o Set up policies like quotas or transformations on the APIs.
o Get insights from analytics.
o Manage users.
3. The developer portal serves as the main web presence for developers, where they can:
o Read API documentation.
o Try out an API via the interactive console.
o Create an account and subscribe to get API keys.
o Access analytics on their own usage.
API Management is about managing APIs. You put an API Management front end on an API to monitor and throttle
usage, manipulate input and output, consolidate several APIs into one endpoint, and so forth. The APIs being
managed can be hosted anywhere.
API Apps is about hosting APIs. The service includes features that facilitate developing and consuming APIs, but it
doesn't do the kinds of monitoring, throttling, manipulating, or consolidating that API Management does. If you don't
need API Management features, you can host APIs in API apps without using API Management.
Note: Some features of API Management and API Apps have similar functions. For example, both can automate CORS
support. When you use the two services together, you would use API Management for CORS since it functions as the front
end to your API apps.
4
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
Note: The Developer Tier is for development, testing, and pilot API programs where high availability is not a concern.
In the Standard and Premium tiers, you can scale your reserved unit count to handle more traffic. The Standard and
Premium tiers provide your API Management service with the most processing power and performance.
Either
1. Build a WebAPI App using Visual Studio and Publish to Azure as App Service API App
OR
2. use Conference Demo API: http://conferenceapi.azurewebsites.net/?format=json
5
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
RequestUri = new Uri("https://dssdemoapimgmt.azure-api.net/conference/<operation name>")
};
using (var response = client.SendAsync(request).Result)
{
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
};
}
}
In Azure API Management (APIM), policies are a powerful capability of the system that allow the publisher to change
the behavior of the API through configuration.
Policies are applied inside the gateway which sits between the API consumer and the managed API. The gateway
receives all requests and usually forwards them unaltered to the underlying API. However, a policy can apply changes
to both the inbound request and outbound response.
The series of specified policy statements is executes in order for a request and a response
<policies>
<inbound>
<!-- statements to be applied to the request go here -->
</inbound>
<backend>
<!-- statements to be applied before the request is forwarded to the backend service go here -->
</backend>
<outbound>
<!-- statements to be applied to the response go here -->
</outbound>
<on-error>
<!-- statements to be applied if there is an error condition go here -->
</on-error>
</policies>
Note: If there is an error during the processing of a request, any remaining steps in the inbound, backend, or outbound
sections are skipped and execution jumps to the statements in the on-error section.
7
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
<cors>
<allowed-origins>
<origin>*</origin>
<!-- allow any -->
<!-- OR a list of one or more specific URIs (case-sensitive) -->
<origin>deccansoft.com</origin>
<!-- URI must include scheme, host, and port. If port is omitted, 80 is assumed for http and 443 is assumed for https. -->
</allowed-origins>
<allowed-methods>
<!-- allow any -->
<method>POST</method>
</allowed-methods>
<allowed-headers>
<!-- allow any -->
<header>*</header>
</allowed-headers>
</cors>
9
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
using System;
using System.Text;
using System.Net.Http;
using System.Web;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
10
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
static void Main()
{
// Define const Key this should be private secret key stored in some safe place
string key = "This is my key, and is also secret";
//And finally when you received token from client you can either validate it or try to read
//var token = handler.ReadJwtToken(tokenString);
//Console.WriteLine(token.Payload.First().Value);
11
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "ff6dea10b5264540846466ffc94e1a02");
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://dssdemoapimgmt.azure-api.net/conference/speakers")
};
request.Headers.Add("Authorization", "Bearer " + tokenString);
var response = client.SendAsync(request).Result;
Console.WriteLine(response.StatusCode);
}
}
Transformation Policies
Let's see how to transform API so it does not reveal a private backend info. For example, you might want to hide the info
about technology stack that is running on the backend. You might also want to hide original URLs that appear in the body
of API's HTTP response and instead redirect them to the APIM gateway.
This section shows how to hide the HTTP headers that you do not want to show to your users. In this example, the
following headers get deleted in the HTTP response:
X-Powered-By
X-AspNet-Version
<policies>
<inbound>
<cross-domain />
<base />
<find-and-replace from="xyz" to="abc" />
</inbound>
</policies>
Policy Expressions
Policy expressions syntax is C# 6.0. Each expression has access to the implicitly provided context variable and an allowed
subset of .NET Framework types.
1. Single statement expressions are enclosed in @(expression), where expression is a well-formed C# expression
statement.
2. Multi-statement expressions are enclosed in @{expression}. All code paths within multi-statement expressions must
@(true)
@((1+1).ToString())
@("Hi There".Length)
@(Regex.Match(context.Response.Headers.GetValueOrDefault("Cache-Control",""), @"max-
age=(?<maxAge>\d+)").Groups["maxAge"]?.Value)
@{
string value;
13
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
if (context.Request.Headers.TryGetValue("Authorization", out value))
{
return Encoding.UTF8.GetString(Convert.FromBase64String(value));
}
else
{
return null;
}
}
API Reference:
https://docs.microsoft.com/en-us/azure/api-management/api-management-policy-
expressions#PolicyExpressionsExamples
Note: Expressions can be used as attribute values or text values in any of the API Management policies, unless the policy
reference specifies otherwise.
Example: To add custom header and query parameters:
<policies>
<inbound>
<set-header name="x-product-name" exists-action="override">
<value>@(context.Product.Name)</value>
</set-header>
<set-query-parameter name="x-username-location" exists-action="override">
<value>@(context.User.Id)</value>
<value>@(context.Deployment.Region)</value>
</set-query-parameter>
<base />
</inbound>
</policies>
16
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
4. Get the thumbprint for the certificate
Fingerprint="$(openssl x509 -in selfsigncert.pem -noout -fingerprint)"
Fingerprint="${Fingerprint//:}"
echo ${Fingerprint#*=}
5. Copy the complete output from the final command to a text file. The output should be a hexadecimal string without
any accompanying text and no colons
6. Edit inbound policy to only allow requests with a valid certificate
API Select API Inboud processing +Add Policy
Replace the <inbound> node of the policy file with the following XML, substituting the thumbprint you copied earlier
for desired-thumbprint:
<inbound>
<choose>
<when condition="@(context.Request.Certificate == null || context.Request.Certificate.Thumbprint != "desired-
thumbprint")" >
<return-response>
<set-status code="403" reason="Invalid client certificate" />
</return-response>
</when>
</choose>
<base />
</inbound>
7. Call the gateway and pass the client certificate
a) To test the API without the certificate, run the following command within the Cloud Shell.
curl -X GET https://[api-gateway-name].azure-api.net/api/Weather/53/-1 \
-H 'Ocp-Apim-Subscription-Key: [Subscription Key]'
This command should return a 403 Client certificate error, and no data will be returned.
b) In the Azure Cloud Shell, to test the API with the certificate, copy and paste the following cURL command, using the
subscription key from the first exercise:
curl -X GET https://[gateway-name].azure-api.net/api/Weather/53/-1 \
-H 'Ocp-Apim-Subscription-Key: [subscription-key]' \
--cert-type pem \
--cert selfsigncert.pem
17
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
Add Caching to Improve Performance
Operations in API Management can be configured for response caching. Response caching can significantly reduce API
latency, bandwidth consumption, and web service load for data that does not change frequently.
<outbound>
<base/>
<cache-store caching-mode="cache-on" duration="3600"/>
</outbound>
</policies>
This this snippet into the outbound section. Note that cache duration is set to the max-age value provided in the Cache-
Control header received from the backend service or to the default value of 5 min if none is found:
<cache-store duration="@{
var header = context.Response.Headers.GetValueOrDefault("Cache-Control","");
var maxAge = Regex.Match(header, @"max-age=(?<maxAge>\d+)").Groups["maxAge"]?.Value;
return (!string.IsNullOrEmpty(maxAge))?int.Parse(maxAge):300;
}"
/>
19
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
<set-header exists-action="override" name="Authorized">
<value>{{ClientAuthorized}}</value>
</set-header>
<set-header exists-action="append" name="TrackingId">
<value>{{TrackingId}}</value>
</set-header>
Monitoring API's
1. Activity Log
2. Diagnostics Log
3. View Metrics
4. Setup Alerts
Handling Revisions
When your API is ready to go and starts to be used by developers, you usually need to take care in making changes to that
API and at the same time not to disrupt callers of your API.
It's also useful to let developers know about the changes you made.
Error Handling
Policies allowed in on-error
choose
set-variable
find-and-replace
return-response
set-header
set-method
set-status
send-request
send-one-way-request
log-to-eventhub
json-to-xml
xml-to-json
When an error occurs and control jumps to the on-error policy section, the error is stored in context.LastError property:
Properties of LastError: Source, Reason, Message, Scope, Section, Path, PolicyId
22
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
6. validate-jwt
24
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
</send-one-way-request>
</on-error>
</policies>
Customers can scale an API Management (APIM) instance by adding and removing units.
A unit is composed of dedicated Azure resources and has a certain load-bearing capacity expressed as a number of
API calls per minute.
Capacity and price of each unit depends on the tier in which the unit exists. You can choose between four tiers:
Developer, Basic, Standard, Premium.
If you need to increase capacity for a service within a tier, you should add a unit. If the tier that is currently selected in
your APIM instance does not allow adding more units, you need to upgrade to a higher-level tier.
25
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
5. Press Save
Configure a custom domain name
There is a number of endpoints to which you can assign a custom domain name. Currently, the following endpoints are
available:
Proxy (default is: <apim-service-name>.azure-api.net),
1. Generate a client certificate: Execute the following command in the same PowerShell window opened earlier
New-SelfSignedCertificate -Type Custom -KeySpec Signature `
-Subject "CN=*.bestazuretraining.com" -KeyExportPolicy Exportable `
-HashAlgorithm sha256 -KeyLength 2048 `
-CertStoreLocation "Cert:\CurrentUser\My" `
-Signer $cert -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2")
2. To obtain the public key (.pfx file)
1. MMC File Add/Remove Snap-In Certificates Add OK
2. Include Private Key . . . Save PFX file.
3. Map it to APIM
1. In the Custom domain name, specify the name you want to use. For example, api.bestazuretraining.com.
Wildcard domain names (for example, *.domain.com) are also supported.
2. In the Certificate, specify a valid .PFX file that you want to upload.
3. If the certificate has a password, enter it in the Password field.
4. Save.
Note: The process of assigning the certificate may take 15 minutes or so.
26
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
1. Azure Active Directory App Registration New Application Registration
2. Name = APIManagementADApp, Application type=Web app/ API, Sign-On URL = <Sign-In URL of Developer Portal of
API Management App>
3. Create
4. Select the New App
1. Properties Copy Application ID to Clipboard / Notepad
2. Keys Generate the New Secret and copy the same to Notepad
3. Reply URL = <Sign-In URL of Developer Portal>-aad (eg https://dssdemoapimgmt.portal.azure-
api.net/signin-aad)
4. Required permissions Click Windows Azure Active Directory Check Application permissions, Read
directory data Check Delegated Permissions, Sign in and read user profile Save Grant Permissions
Yes
How to log in to the Developer portal using an Azure Active Directory account
11. Visit the Sign-In page of the Developer portal
12. click Azure Active Directory.
27
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
13. Provide the Username and Password for the account create in Azure AD using default domain name.
Reference: https://docs.microsoft.com/en-in/azure/api-management/api-management-howto-aad
Delegated Authentication
Documentation:
https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-setup-delegation
namespace MyAPIDemoApp.Controllers
{
public class LoginController : Controller
{
28
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
// GET: Logoin
public ActionResult Index(string operation, string returnUrl, string salt, string sig)
{
//string s = $"{operation} - {returnUrl} - {salt} - {sig}";
return View();
}
serializer.Serialize(jsonWriter, value);
return writer.GetStringBuilder().ToString();
}
29
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
[HttpPost]
public async Task<ActionResult> Index(FormCollection col)
{
string token = "SharedAccessSignature
integration&201801251311&YYF9t4Cc/R9iGd5D1zeg8aK6RKQrHSleaDjdUV6eEv3gaXRZj2NhgdcWXncaBYbdWaPFBdn6ozx
Nb4PqFB8eRQ==";
string baseUrl = "https://dssapimgmt.management.azure-api.net/";
//Create a User
using (var clientForNewUser = new HttpClient())
{
clientForNewUser.BaseAddress = new Uri(baseUrl);
clientForNewUser.DefaultRequestHeaders.Add("Authorization", token);
clientForNewUser.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json"));
//User Object required for adding a new user to API Management Service
var ApimUser = new
{
firstName = uid + "-FUser",
lastName = "LUser",
email = $"User-{uid}@gmail.com",
password = "Abcd@1234",
state = "active"
};
30
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
clientToLoginUsingSSO.BaseAddress = new Uri("https://dssapimgmt.management.azure-api.net/");
clientToLoginUsingSSO.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("text/json"));
clientToLoginUsingSSO.DefaultRequestHeaders.Add("Authorization", token);
var resp = await clientToLoginUsingSSO.PostAsync("/users/" + uid + "/generateSsoUrl?api-version=2017-03-01",
new StringContent("", Encoding.UTF8, "text/json"));
if (resp.IsSuccessStatusCode)
{
HttpContent receiveStream = resp.Content;
var SsoUrlJson = await receiveStream.ReadAsStringAsync();
var su = DeserializeToJson<SsoUrl>(SsoUrlJson);
Response.Redirect(su.value);
}
}
else
{
@ViewBag.message = "APIM REST Connection Error: " + response.StatusCode;
}
}
return View();
}
}
}
31
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services API Management Service
Call the API unsuccessfully from the developer portal
Register the developer portal as an AAD application
Configure an API Management OAuth 2.0 authorization server
Enable OAuth 2.0 user authorization for the Calculator API
Successfully call the Calculator API from the developer portal
Configure a desktop application to call the API
Configure a JWT validation policy to pre-authorize requests
32
Deccansoft Software Services H.No: 153, A/4, Balamrai, Rasoolpura, Secunderabad-500003 TELANGANA, NDIA.
http://www.deccansoft.com | http://www.bestdotnettraining.com
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)