Generating an SDK - Ed-Fi Roster
- Cy Jones (Deactivated)
- Stephen Fuqua
- Ian Christopher (Deactivated)
Overview
To make it easier to interface with an Ed-Fi API instance, OpenAPI Generator can be used to generate a client library. The following section outlines how to use code generation to create an Ed-Fi ODS / API Client SDK.
The high-level steps are:
- Step 1. Install Latest Version of Java
- Step 2. Download the OpenAPI Generator JAR File
- Step 3. Generate the SDK Source Files
- Step 4. (Optional) Using the SDK in a Sample C# Console Application
Each step is outlined in detail below.
Step 1. Install Latest version of Java
The OpenAPI Generator is a Java application and requires a modern version of Java to run. If Java is not already installed, navigate to https://java.com/en/download/ (Java.com) or https://adoptopenjdk.net/ (OpenJDK), and download the latest installer. Run the installer to install the latest version of Java. The code generation tool leverages Java, but it does output C# code, among other supported languages/frameworks such as Java, Python, JavaScript/Node.js, Ruby, and other languages.
Step 2. Download the OpenAPI Generator JAR File
Download the latest version of the OpenAPI Generator JAR (v5.1.1+). Windows users can download the JAR file using wget or Invoke-WebRequest in PowerShell (3.0+) as follows:
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.4.0/openapi-generator-cli-5.4.0.jar
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.4.0/openapi-generator-cli-5.4.0.jar
For more information and download options, visit OpenAPI generator's GitHub installation section.
Step 3. Generate the SDK Source Files
The SDK source files are generated using Swagger metadata via a few simple PowerShell commands. You can see the available metadata endpoints for SDK generation at https://api.ed-fi.org/v5.2/api/metadata?sdk=true. For the Enrollments, Change Queries, and Resources API-based SDK, the following commands can be used.
OpenAPI Generator outputs in many popular programming languages. Please see https://openapi-generator.tech/docs/generators for a list of options. Below, examples are provided for .NET Core (C#), Python, Javascript, and Ruby.
java -jar openapi-generator-cli.jar generate -g csharp-netcore -i https://api.ed-fi.org/v5.2/api/metadata/composites/v1/ed-fi/enrollment/swagger.json --api-package Api.EnrollmentComposites --model-package Models.EnrollmentComposites -o csharp-netcore --additional-properties=netCoreProjectFile --additional-properties=packageName='EdFi.Roster.Sdk' --additional-properties=targetFramework=netcoreapp3.1 --additional-properties=modelPropertyNaming=PascalCase java -jar openapi-generator-cli.jar generate -g csharp-netcore -i https://api.ed-fi.org/v5.2/api/metadata/changequeries/v1/swagger.json --api-package Api.ChangeQueries --model-package Models.ChangeQueries -o csharp-netcore --additional-properties=netCoreProjectFile --additional-properties=packageName='EdFi.Roster.Sdk' --additional-properties=targetFramework=netcoreapp3.1 --additional-properties=modelPropertyNaming=PascalCase java -jar openapi-generator-cli.jar generate -g csharp-netcore -i https://api.ed-fi.org/v5.2/api/metadata/data/v3/resources/swagger.json --api-package Api.Resources --model-package Models.Resources -o csharp-netcore --additional-properties=netCoreProjectFile --additional-properties=packageName='EdFi.Roster.Sdk' --additional-properties=targetFramework=netcoreapp3.1 --additional-properties=modelPropertyNaming=PascalCase
This generates a whole solution (EdFi.Roster.Sdk.sln) under the "csharp-netcore" folder. However, only a few elements are needed for the final SDK project:
- The .csproj file contents (for NuGet package references).
- The contents of "Api.EnrollmentComposites", "Api.ChangeQueries", and "Api.Resources" folders.
- The contents of "Client" folder.
- The contents of "Models.EnrollmentComposites", "Models.ChangeQueries", and "Models.Resources" folders.
java -jar openapi-generator-cli.jar generate -g java -i https://api.ed-fi.org/v5.2/api/metadata/composites/v1/ed-fi/enrollment/swagger.json --api-package Api.EnrollmentComposites --model-package Models.EnrollmentComposites -o java java -jar openapi-generator-cli.jar generate -g java -i https://api.ed-fi.org/v5.2/api/metadata/changequeries/v1/swagger.json --api-package Api.ChangeQueries --model-package Models.ChangeQueries -o java java -jar openapi-generator-cli.jar generate -g java -i https://api.ed-fi.org/v5.2/api/metadata/data/v3/resources/swagger.json --api-package Api.Resources --model-package Models.Resources -o java
java -jar openapi-generator-cli.jar generate -g python -i https://api.ed-fi.org/v5.2/api/metadata/composites/v1/ed-fi/enrollment/swagger.json --api-package Api.EnrollmentComposites --model-package Models.EnrollmentComposites -o python java -jar openapi-generator-cli.jar generate -g python -i https://api.ed-fi.org/v5.2/api/metadata/changequeries/v1/swagger.json --api-package Api.ChangeQueries --model-package Models.ChangeQueries -o python java -jar openapi-generator-cli.jar generate -g python -i https://api.ed-fi.org/v5.2/api/metadata/data/v3/resources/swagger.json --api-package Api.Resources --model-package Models.Resources -o python
java -jar openapi-generator-cli.jar generate -g javascript -i https://api.ed-fi.org/v5.2/api/metadata/composites/v1/ed-fi/enrollment/swagger.json --api-package Api.EnrollmentComposites --model-package Models.EnrollmentComposites -o javascript java -jar openapi-generator-cli.jar generate -g javascript -i https://api.ed-fi.org/v5.2/api/metadata/changequeries/v1/swagger.json --api-package Api.ChangeQueries --model-package Models.ChangeQueries -o javascript java -jar openapi-generator-cli.jar generate -g javascript -i https://api.ed-fi.org/v5.2/api/metadata/data/v3/resources/swagger.json --api-package Api.Resources --model-package Models.Resources -o javascript
java -jar openapi-generator-cli.jar generate -g ruby -i https://api.ed-fi.org/v5.2/api/metadata/composites/v1/ed-fi/enrollment/swagger.json --api-package Api.EnrollmentComposites --model-package Models.EnrollmentComposites -o ruby java -jar openapi-generator-cli.jar generate -g ruby -i https://api.ed-fi.org/v5.2/api/metadata/changequeries/v1/swagger.json --api-package Api.ChangeQueries --model-package Models.ChangeQueries -o ruby java -jar openapi-generator-cli.jar generate -g ruby -i https://api.ed-fi.org/v5.2/api/metadata/data/v3/resources/swagger.json --api-package Api.Resources --model-package Models.Resources -o ruby
Step 4. (Optional) Using the SDK in a Sample C# Console Application
The generated SDK files can be referenced as a project in a sample Roster Starter Kit solution. The following section details how to use the generated solution above ("EdFi.Roster.Sdk.sln") and create a sample C# console application using the generated SDK project to make an Enrollments API call.
- Open "EdFi.Roster.Sdk.sln" (under the csharp-netcore folder generated above) in Visual Studio (VS 2019 is used in the screenshots).
- Build the solution.
- Right-click on the solution and add a new project. Choose the type C# Console Application (.NET Core). Name the project "EdFi.Roster.SdkClient".
- Right-click on Edfi.Roster.SdkClient > Set as Startup Project.
- In Solution Explorer, right-click EdFi.Roster.SdkClient project and click Add > Project Reference.
- In the "Reference Manager" window, select EdFi.Roster.Sdk, and then click OK.
Open the Program.cs file and add the following
using
statements at the top of the file:using System; using EdFi.Roster.Sdk.Api.EnrollmentComposites; using EdFi.Roster.Sdk.Client;
Edit the Program.cs file and paste the following into the Main method. The client and key are using a publicly available sandbox environment with sample data hosted by the Ed-Fi Alliance.
// Trust all SSL certs -- needed unless signed SSL certificates are configured. System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); //Explicitly configures outgoing network calls to use the latest version of TLS where possible. //Due to our reliance on some older libraries, the.NET framework won't necessarily default //to the latest unless we explicitly request it. Some hosting environments will not allow older versions //of TLS, and thus calls can fail without this extra configuration. System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; // Oauth configuration var oauthUrl = "https://api.ed-fi.org:443/v5.2/api"; var clientKey = "RvcohKz9zHI4"; var clientSecret = "E1iEFusaNf81xzCxwHfbolkC"; // TokenRetriever makes the oauth calls. It has RestSharp dependency, install via NuGet var tokenRetriever = new TokenRetriever(oauthUrl, clientKey, clientSecret); // Plug Oauth access token. Tokens will need to be refreshed when they expire var configuration = new Configuration() { AccessToken = tokenRetriever.ObtainNewBearerToken(), BasePath = "https://api.ed-fi.org:443/v5.2/api/composites/v1" }; // GET schools var api = new SchoolsApi(configuration); var response = api.GetSchoolsWithHttpInfo(null, null); // offset, limit var httpReponseCode = response.StatusCode; // returns System.Net.HttpStatusCode.OK var schools = response.Data; Console.WriteLine("Response code is " + httpReponseCode); foreach (var school in schools) { Console.WriteLine(school.NameOfInstitution); } Console.WriteLine(); Console.WriteLine("Hit ENTER key to continue..."); Console.ReadLine();
Add a .cs file named TokenRetriever.cs and copy the following code to help with OAuth integration.
using System.Net; using System.Security.Authentication; using RestSharp; namespace EdFi.Roster.SdkClient { public class TokenRetriever { private string oauthUrl; private string clientKey; private string clientSecret; /// <summary> /// /// </summary> /// <param name="oauthUrl"></param> /// <param name="clientKey"></param> /// <param name="clientSecret"></param> public TokenRetriever(string oauthUrl, string clientKey, string clientSecret) { this.oauthUrl = oauthUrl; this.clientKey = clientKey; this.clientSecret = clientSecret; } public string ObtainNewBearerToken() { var oauthClient = new RestClient(oauthUrl); return GetBearerToken(oauthClient); } private string GetBearerToken(IRestClient oauthClient) { var bearerTokenRequest = new RestRequest("oauth/token", Method.POST); bearerTokenRequest.AddParameter("Client_id", clientKey); bearerTokenRequest.AddParameter("Client_secret", clientSecret); bearerTokenRequest.AddParameter("Grant_type", "client_credentials"); var bearerTokenResponse = oauthClient.Execute<BearerTokenResponse>(bearerTokenRequest); if (bearerTokenResponse.StatusCode != HttpStatusCode.OK) { throw new AuthenticationException("Unable to retrieve an access token. Error message: " + bearerTokenResponse.ErrorMessage); } if (bearerTokenResponse.Data.Error != null || bearerTokenResponse.Data.TokenType != "bearer") { throw new AuthenticationException( "Unable to retrieve an access token. Please verify that your application secret is correct."); } return bearerTokenResponse.Data.AccessToken; } } internal class BearerTokenResponse { public string AccessToken { get; set; } public string ExpiresIn { get; set; } public string TokenType { get; set; } public string Error { get; set; } } }
- Build the project and run it without debugging (Ctrl+F5) and you should see the following results:
With that, you're done!
This exercise leveraged a publicly available instance of the API (v5.2). If you're working with a specific platform host, a great next step is to use these same techniques to generate an SDK for that platform. If the platform host has extended the data model, your new code will automatically include those structures in the data access components in the generated code.