V10 ResourcesWeb API
ResourcesWeb API
Web API
Back | List of Articles

How to extend the Web API?

Last changed in 02/12/2020

The Web API of the version 10 of the PRIMAVERA ERP is an innovative technological piece that allows the companies to integrate the ERP with other systems.

The Web API presents, as REST services, most of the native methods of the ERP API, but there are others that were not considered. When extending this Web API, it is possible to add new features that were not included natively, as well as other features that the integrator partner might need. These new methods will use the same end point.

Procedure

To demonstrate the extension capacity, in this article we will use as an example the printing of a sales document as a PDF ready to be presented.

Requirements

  • Primavera ERP with Web API installed and licensed
  • Visual Studio & .NET Framework 4.7.1

Step 1 - Create the project

First, it is necessary to create a project with Visual Studio in order to create a class that adds more features. This project must be of the type Class Library (.NET Framework).

Step 2 - Packages

The following packages must be added to the project, taking into account its versions , considering that these are the version used in the assemblies, both in the ERP and in the Web API:

  • "Microsoft.AspNet.WebApi" version="5.2.6"
  • "Microsoft.Owin" version="4.0.0"

Step 3 - Class naming convention

The class added to the project must obey two requirements in order to be recognized by the Web API:

  1. The first requirement is related with its name. It must contain the suffix Controller.
  2. This class must also be based on the class Assembly System.Web.Http.ApiControler
public class ClassExtendedController: ApiController

In this example, we call the class "ClassExtendedController".

Step 4 - RoutePrefix

As with any Web API class, this one also needs the annotation RoutePrefix that must be the same as the class name, without the suffix Controller.

[RoutePrefix("ClassExtended")]
public class ClassExtendedController: ApiController

Step 5 - Coding

As explained, the example shown is printing a sales document in PDF format. It will be a HttpGet request with the following route:

[Authorize]
[Route("PrintSalesDocToPDF/{TipoDoc}/{Serie}/{Numdoc}/{Filial}/{Numvias}/{NomeReport}/{SegundaVia}/{NomePDF}/{EntidadeFacturacao}")]
[HttpGet]

The complete code is the following:

[Authorize]
[Route("PrintSalesDocToPDF/{TipoDoc}/{Serie}/{Numdoc}/{Filial}/{Numvias}/{NomeReport}/{SegundaVia}/{NomePDF}/{EntidadeFacturacao}")]
[HttpGet]
public HttpResponseMessage PrintSalesDocToPDF(string TipoDoc, string Serie, int Numdoc, string Filial, int Numvias, string NomeReport, bool SegundaVia, string NomePDF, int EntidadeFacturacao)
{
	try
	{
		HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest);

		// Ensure the extension is defined
		if (string.IsNullOrWhiteSpace(Path.GetExtension(NomePDF)))
		{
			NomePDF += ".pdf";
		}

		// Ensure a physical location to store the generated PDF
		if (string.IsNullOrWhiteSpace(Path.GetDirectoryName(NomePDF)))
		{
			NomePDF = Path.Combine(Path.GetTempPath(), NomePDF);
		}

		// Prints the document to pdf using API
		bool imprimedocumento = ProductContext.MotorLE.Vendas.Documentos.ImprimeDocumento(TipoDoc, Serie, Numdoc, Filial, Numvias, NomeReport, SegundaVia, NomePDF, EntidadeFacturacao);

		// Prepares the response
		if (imprimedocumento)
		{
			var dataBytes = File.ReadAllBytes(NomePDF);
			var dataStream = new MemoryStream(dataBytes);

			byte[] buffer = new byte[0];
			buffer = dataStream.ToArray();

			var contentLength = buffer.Length;

			var statuscode = HttpStatusCode.OK;
			response = Request.CreateResponse(statuscode);
			response.Content = new StreamContent(new MemoryStream(buffer));
			response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
			response.Content.Headers.ContentLength = contentLength;

			if (ContentDispositionHeaderValue.TryParse("inline; filename=" + NomePDF, out ContentDispositionHeaderValue contentDisposition))
			{
				response.Content.Headers.ContentDisposition = contentDisposition;
			}
		}

		return response;
	}
	catch (Exception ex)
	{
		throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
	}
}

This service, that prints a sales document, uses the method ImprimeDocumento available in the sales module API. The ERP context can be accessed in the Web API, without it being necessary to implement another mechanism. All safety questions are also assured.

The access to the ERP context is granted by the class ProductContext on the assembly Primavera.WebAPI.Integration, and it is necessary to reference it in the project.

Step 6 - Compiling and Deployment

After having it all assembled as previously explained, simply compile the project.

In the project output, the assembly will be generated and it will have to be copied too the Web API folder, generally for the folder "PRIMAVERASG100AplWebApibin".

Step 7 - Test

To test this code, you can use the Postman.

After requesting the token, you can request to print a document using the following route:

{{apiUrl}}ClassExtended/PrintSalesDocToPDF/{TipoDoc}/{Serie}/{Numdoc}/{Filial}/{Numvias}/{NomeReport}/{SegundaVia}/{NomePDF}/{EntidadeFacturacao}

The following example prints a copy of the GT C/1 document, of the branch 000, using the report GCPVLS01. The entity to be printed is the one that matches the invoicing entity and the name of the file to be returned is docGT1.pdf.

{{apiUrl}}ClassExtended/PrintSalesDocToPDF/GT/C/1/000/1/GCPVLS01/false/docGTC1/1

Considering that Postman does not have a document preview in PDF format, in the response we can save it to a document and validate if it happens as expected.

Conclusion

Creating extensions to the Web API is the best way to take full advantage of this technology, without having to create new web services. All the services not available natively can be implemented, as well as any other service resulting from an implementation service.

Bookmark or share this article
Esta página foi útil?
Obrigado pelo seu voto.

login para deixar a sua opinião.

Obrigado pelo seu feedback. Iremos analisá-lo para continuarmos a melhorar!
Artigos Relacionados
Utilizar o Postman para testar a WebAPI Formato dos pedidos Web API ERP10 Características da Web API Como executar listas na WebAPI? Web API - Conceitos e Arquitetura