Create an API Management instance
Note
To complete this tutorial, you need an Azure account. If you don't have an account, you can create a free account in just a couple of minutes. For details, see
Azure Free Trial.
The first step in working with API Management is to create a service instance. Sign in to the
Azure Portal and click
New,
Web + Mobile,
API Management.
For Name, specify a unique sub-domain name to use for the service URL.
Choose the desired Subscription, Resource group and Location for your service instance.
Enter Contoso Ltd. for the Organization Name, and enter your email address in the Administrator E-Mail field.
API Management service instances are available in three tiers: Developer, Standard, and Premium.
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. You can complete this tutorial by using any tier. For more information about API Management tiers, see
API Management pricing.
Click Create to start provisioning your service instance.
Once the service instance is created, the next step is to create or import an API.
Import an API
An API consists of a set of operations that can be invoked from a client application. API operations are proxied to existing web services.
APIs can be created (and operations can be added) manually, or they can be imported. In this tutorial, we will import the API for a sample calculator web service provided by Microsoft and hosted on Azure.
APIs are configured from the publisher portal. To reach it, click Publisher portal from the service toolbar.
To import the calculator API, click APIs from the API Management menu on the left, and then click Import API.
Perform the following steps to configure the calculator API:
- Click From URL, enter http://calcapi.cloudapp.net/calcapi.json into the Specification document URL text box, and click the Swagger radio button.
- Type calc into the Web API URL suffix text box.
- Click in the Products (optional) box and choose Starter.
- Click Save to import the API.
OR YOU CAN ADD JSON FILE FROM YOUR LOCAL
Run your Api on Internet Explorer . And Save Jshon File. And Uplaod it.
Note
API Management currently supports both 1.2 and 2.0 version of Swagger document for import. Make sure that, even though
Swagger 2.0 specification declares that
host
,
basePath
, and
schemes
properties are optional, your Swagger 2.0 document
MUST contain those properties; otherwise it won't get imported.
Once the API is imported, the summary page for the API is displayed in the publisher portal.
The API section has several tabs. The
Summary tab displays basic metrics and information about the API. The
Settings tab is used to view and edit the configuration for an API. The
Operations tab is used to manage the API's operations. The
Security tab can be used to configure gateway authentication for the backend server by using Basic authentication or
mutual certificate authentication, and to configure
user authorization by using OAuth 2.0. The
Issues tab is used to view issues reported by the developers who are using your APIs. The
Products tab is used to configure the products that contain this API.
1
By default, each API Management instance comes with two sample products:
In this tutorial, the Basic Calculator API was added to the Starter product when the API was imported.
In order to make calls to an API, developers must first subscribe to a product that gives them access to it. Developers can subscribe to products in the developer portal, or administrators can subscribe developers to products in the publisher portal. You are an administrator since you created the API Management instance in the previous steps in the tutorial, so you are already subscribed to every product by default.
Call an operation from the developer portal
Operations can be called directly from the developer portal, which provides a convenient way to view and test the operations of an API. In this tutorial step, you will call the Basic Calculator API's Add two integers operation. Click Developer portal from the menu at the top right of the publisher portal.
Click APIs from the top menu, and then click Basic Calculator to see the available operations.
Note the sample descriptions and parameters that were imported along with the API and operations, providing documentation for the developers that will use this operation. These descriptions can also be added when operations are added manually.
To call the Add two integers operation, click Try it.
You can enter some values for the parameters or keep the defaults, and then click Send.
After an operation is invoked, the developer portal displays the Response status, the Response headers, and any Response content.
View analytics
To view analytics for Basic Calculator, switch back to the publisher portal by selecting Managefrom the menu at the top right of the developer portal.
The default view for the publisher portal is the Dashboard, which provides an overview of your API Management instance.
Hover the mouse over the chart for Basic Calculator to see the specific metrics for the usage of the API for a given time period.
Note
If you don't see any lines on your chart, switch back to the developer portal and make some calls into the API, wait a few moments, and then come back to the dashboard.
Click View Details to view the summary page for the API, including a larger version of the displayed metrics.
For detailed metrics and reports, click Analytics from the API Management menu on the left.
Main Thing is Create Policy
For API Security Reason You add below line in your Web API config
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Filters.Add(new UseApiManagementAttributes());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
==============================
Next Step you add a folder which name is Filters on Api. and add a class name UseApiManagementAttributes.
And add below code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;
using System.Globalization;
using System.Net;
namespace API.Filters
{
public class UseApiManagementAttributes:ActionFilterAttribute
{
#region Methods
public override void OnActionExecuting(HttpActionContext actionContext)
{
var configkey = ConfigurationManager.AppSettings["Api.Key"];
IEnumerable<string> Keys = null;
var error = false;
var checkKey = true;
if(String.IsNullOrEmpty(configkey))
{
error = true;
}
else
{
if (actionContext.Request.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
//Seems like we are called from Azure API Management here.Be aware that this code is anythng.
//but secure. It simple assume that Ocp-Apim-Subscription-Key and User-Agent are present in the header
//This is Because of the lack of certificate in current azure portal.
error = !actionContext.Request.Headers.TryGetValues("Ocp-Apim-Subscription-Key", out Keys) || Keys.Any();
if(!error)
{
//if the magic Apim-key is present check now, if the agent is correct.
var agent = string.Empty;
var agents = actionContext.Request.Headers.GetValues("User-Agent");
error=!agent.Any() || !agents.First().Equals("EMA-Gateway",StringComparison.OrdinalIgnoreCase);
}
//We don't need to check the key because it is managed by API Management.
checkKey = false;
}
else if(actionContext.Request.Headers.Contains("api_Key"))
{
//This could be valid APi call using a static secerate API from request.
error=!actionContext.Request.Headers.TryGetValues("api_Key",out Keys)||!Keys.Any();
}
else if(actionContext.Request.RequestUri.ParseQueryString().HasKeys() && actionContext.Request.RequestUri.ParseQueryString().HasKeys())
{
//This could be a valid API call a static API key from URL like swagger case.
Keys = new[] { actionContext.Request.RequestUri.ParseQueryString().Get("api_Key") };
}
else
{
error = true;
}
}
if(!error && checkKey && !Keys.First().Equals(configkey,StringComparison.Ordinal))
{
error = true;
}
if(error)
{
var message = string.Format(CultureInfo.InvariantCulture, "Request are only allocated using the api management URLS.");
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.UseProxy, message);
return;
}
base.OnActionExecuting(actionContext);
}
#endregion
}
}
===================
Set on API Web Config Below Code
<appSettings>
<add key="Api.Key" value="1234" />
</appSettings>
===========================
Next When you call api on your Project Below code Example
===========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class APITEST : System.Web.UI.Page
{
HttpClient client = new HttpClient();
List<Department> DepartmentList = null;
protected void Page_Load(object sender, EventArgs e)
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "dbe20779b9ce47cab9e60c132da99e82");
var path = "https://swashapimanagementservice.azure-api.net/Trinty/api/Department";
// var appsurl = ConfigurationManager.AppSettings["APIPath"].ToString();
client.BaseAddress = new Uri(path);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
GetData();
}
private List<Department> GetData()
{
HttpResponseMessage skill = client.GetAsync("Department").Result;
if (skill.IsSuccessStatusCode)
{
DepartmentList = skill.Content.ReadAsAsync<List<Department>>().Result;
return DepartmentList.Where(a => a.IsActive == true).OrderByDescending(a => a.Department_ID).ToList();
}
else
{
return null;
}
}
}