Exploring the API /businessnxtapi/exploring_api section This section introduces testing GraphQL endpoint queries using tools like GraphiQL and Postman, and details the POST request structure with a "GetCustomers" query example. 2024-09-24T15:57:29+02:00 # Exploring the API This section introduces testing GraphQL endpoint queries using tools like GraphiQL and Postman, and details the POST request structure with a "GetCustomers" query example. For testing, you can run requests to the GraphQL endpoint with your preferred tools. We recommend: - [GraphiQL](https://github.com/graphql/graphiql) - a web-based GraphQL IDE - [Postman](https://www.postman.com/) - the widely used collaboration platform for API development, with built-int GraphQL support - [Insomnia](https://insomnia.rest/) - similar to Postman, also with built-in support for GraphQL - [Curl](https://curl.se/) - a widely used command line tool for transfering data using a variety of network protocols, including HTTP/HTTPs The general form of a GraphQL query is as follows: - the request is a POST - the content type is `application/json` - the body is a JSON with the form shown below, where the value of `query` is a serialized JSON (properly escaped) and `variables` is a JSON object. The `variables` property can be skipped or could be set to `null` if there are no GraphQL variables in the query. ```json { "query" : "...", "variables" : {} } ``` The following snippet shows a query example: ```json { "query":"query GetCustomers($companyNo: Int, $pageSize: Int, $after :String)\n{\n useCompany(no: $companyNo)\n {\n associate(first: $pageSize, after: $after)\n {\n totalCount\n pageInfo\n {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n items\n {\n associateNo\n customerNo\n name\n }\n }\n }\n}", "variables":{"companyNo":9112233,"pageSize":5}, "operationName":"GetCustomers" } ``` In this example, you can also see the property `operationName` that contains the name of the operation (that follows the `query` or `mutation` keyword). > [!NOTE] > > The topic of GraphQL variables is addressed later in the tutorial in section [Named queries and parameters](/businessnxtapi/features/parameters/). GraphiQL /businessnxtapi/exploring_api/graphiql page Explore and test GraphQL queries using GraphiQL, a web IDE with features like schema auto-fetch, query auto-complete, and documentation exploration. 2024-09-24T15:57:29+02:00 # GraphiQL Explore and test GraphQL queries using GraphiQL, a web IDE with features like schema auto-fetch, query auto-complete, and documentation exploration. You can explore the API and execute queries using GraphiQL, which is an web-based integrated development environment (IDE) for GraphQL. GraphiQL enables you to explore the GraphQL schema as well as building and executing queries. This is a very useful tool for getting familiar with our API, preparing your queries, and testing them. For these reasons, GraphiQL provides a better experience than the tools mentioned earlier, enabling you to familiazize yourself with the GraphQL schema and become productive in a short period. ![](../graphiql.png) GraphiQL features include the following: * automatic fetching of schema * exploration of documentation (built from the schema) * navigation from the query to documentation by hovering the cursor over a node in the query * auto completion for query and variables (`CTRL` + `SPACE`) * history of most recent queries (allowing you to run previous queries) * multiple tabs and multiple queries per tab * query prettyfier * syntax coloring * editing of HTTP headers ![graphiql_autocomplete](../graphiql_autocomplete.png) ![graphiql_history](../graphiql_history.png) > [!TIP] > You can learn more about GraphiQL from the project documentation. See [GraphiQL IDE](https://github.com/graphql/graphiql). ## Endpoint The Business NXT GraphiQL endpoint is . > [!IMPORTANT] > You must be authenticated with your Visma Connect user in order to access GraphiQL. Postman /businessnxtapi/exploring_api/postman page Postman supports GraphQL requests with built-in tools or raw POST requests, using application/json content type for queries and variables. 2024-09-24T15:57:29+02:00 # Postman Postman supports GraphQL requests with built-in tools or raw POST requests, using application/json content type for queries and variables. Postman has built-in support for GraphQL. You can make requests selecting GraphQL for the body type. There are two fields, **QUERY** and **GRAPHQL VARIABLES** where you can provide the query and variables. ![GraphQL query in Postman](../postman1.png) You can achieve the same making a raw POST request, with the content type set to `application/json` and the body with the form explained in the beginning of this section. ![GraphQL raw query in Postman](../postman2.png) > [!TIP] > You can learn more about Postman from its official [Learning center](https://learning.postman.com/docs/getting-started/introduction/). Insomnia /businessnxtapi/exploring_api/insomnia page Insomnia offers superior GraphQL support with schema fetching, autocomplete, and an interactive schema explorer for efficient API management. 2024-09-24T15:57:29+02:00 # Insomnia Insomnia offers superior GraphQL support with schema fetching, autocomplete, and an interactive schema explorer for efficient API management. Insomnia is an application that has many similarities with Postman, although it provides better support for working with GraphQL schemas. ![GraphQL query in Insomnia](../insomnia1.png) You can use the schema button in the query window to fetch or refresh the schema and then you get auto complete suport in the query editor. ![GraphQL schema support in Insomnia](../insomnia2.png) Insomnia allows you to explore the schema documentation by using the *Show Documentation* option from the schema button. This is shown in the following image: ![GraphQL schema options in Insomnia](../insomnia3.png) The schema explorer can also be opened by hovering the cursor over any part of the query and then clickin on the links in the tooltip window. ![GraphQL schema tooltip in Insomnia](../insomnia4.png) The schema explorer allows you to navigate through the schema and understand its structure. ![GraphQL schema explorer in Insomnia](../insomnia5.png) > [!TIP] > You can learn more about Insomnia from its official documentation. See [Insomnia Docs](https://docs.insomnia.rest/). Making requests from code /businessnxtapi/exploring_api/code page Learn how to make programmatic requests in C#/.NET 5 to execute GraphQL queries and deserialize JSON responses. 2025-04-15T09:48:42+02:00 # Making requests from code Learn how to make programmatic requests in C#/.NET 5 to execute GraphQL queries and deserialize JSON responses. In this section, we will consider making requests programatically to execute the following query: ```graphql { title = "Query" } query read_glas($cid : Int, $pagesize : Int){ useCompany(no: $cid) { generalLedgerAccount(first: $pagesize) { totalCount pageInfo { hasNextPage hasPreviousPage startCursor endCursor } items { accountNo name } } } } ``` ```graphql { title = "Result" } { "data": { "useCompany": { "generalLedgerAccount": { "totalCount": 344, "pageInfo": { "hasNextPage": true, "hasPreviousPage": false, "startCursor": "MA==", "endCursor": "MjAw" }, "items": [ { "accountNo": 1000, "name": "Forskning og utvikling" }, { "accountNo": 1020, "name": "Konsesjoner" }, { "accountNo": 1030, "name": "Patenter" } ] } } } } ``` > [!IMPORTANT] > The code for the example described here is available on GitHub at [GraphQLSamples/SimpleQuery](https://github.com/Visma-Business/GraphQLSamples/tree/main/SimpleQuery). ## C# / .NET 5 Example If you need to make requests programatically and are using C# and .NET 5, you can do the following: 1. Create a class to contain the actual query and potential variables. ```cs class QueryRequest { [JsonPropertyName("query")] public string query { get; set; } [JsonPropertyName("variables")] public Dictionary variables { get; set; } } ``` **Note**: The name of the C# class and its properties are not that important. However, the JSON text that is being sent in the body of the POST request must have the form shown in the following snippet (that contains a query for reading a first page of 100 records from the general ledger account table). Notice that `query` and `variable` must be in lower-case. ```json { "query": "query read_glas($cid : Int, $pagesize : Int){\r\n useCompany(no: $cid) {\r\n generalLedgerAccount(first: $pagesize) {\r\n totalCount\r\n pageInfo {\r\n hasNextPage\r\n hasPreviousPage\r\n startCursor\r\n endCursor\r\n }\r\n items {\r\n accountNo\r\n name\r\n }\r\n }\r\n }\r\n}", "variables": { "cid" : 9112233, "pagesize" : 100 } } ``` You can use JSON attributes (they are similar whether you use *Json.NET* or *System.Text.Json*) to ensure the serialized JSON document has the correct shape regarless of the names of the C# classes, properties, or fields. 2. Create classes to model the expected response, so that you can deserialize the JSON object returned by the server. ```cs public class GeneralLedgerAccountResponse { public Data data { get; set; } } public class Data { public Usecompany useCompany { get; set; } } public class Usecompany { public GeneralLedgerAccountConnection generalLedgerAccount { get; set; } } public class GeneralLedgerAccountConnection { public int totalCount { get; set; } public PageInfo pageInfo { get; set; } public GeneralLedgerAccount[] items { get; set; } } public class PageInfo { public bool hasNextPage { get; set; } public bool hasPreviousPage { get; set; } public string startCursor { get; set; } public string endCursor { get; set; } } public class GeneralLedgerAccount { public int accountNo { get; set; } public string name { get; set; } } ``` 3. Create a generic method that can execute a request and return the deserialized result. ```cs class Program { private static readonly HttpClient _client = new(); private static async Task ExecuteQuery(QueryRequest request, string url, string accessToken) { try { _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); using var response = await _client.PostAsJsonAsync(url, request); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadFromJsonAsync(); return content; } catch (HttpRequestException ex) { Console.Error.WriteLine($"{ex.Message} (code: {ex.StatusCode.Value})"); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } return default; } } ``` 4. Obtain an access token programatically. [This is covered in Examples for setting up authorization: .NET Code Sample](/businessnxtapi/authentication/web/examples/code/). 5. Create a request string, execute it, and process the result. ```cs class Program { static async Task Main(string[] args) { var url = "https://business.visma.net/api/graphql"; var accessToken = "..."; var companyId = ...; var pageSize = 100; var request = new QueryRequest() { query = @"query read_glas($cid : Int, $pagesize : Int){ useCompany(no: $cid) { generalLedgerAccount(first: $pagesize) { totalCount pageInfo { hasNextPage hasPreviousPage startCursor endCursor } items { accountNo name } } } }", variables = new Dictionary { {"cid", companyId}, {"$pagesize", pageSize} } }; var result = await ExecuteQuery(request, url, accessToken); if (result?.data?.useCompany?.generalLedgerAccount?.items is object) { foreach (var gla in result.data.useCompany.generalLedgerAccount.items) { Console.WriteLine($"{gla.accountNo} - {gla.name}"); } } } } ```