DEV Community

Alexander Nitrovich
Alexander Nitrovich

Posted on • Originally published at blog.eurovalidate.com

Validate VAT in Go (full example)

Ensuring that VAT numbers are accurate is integral for businesses in e-commerce and fintech sectors. Using a reliable developer-first API for VAT validation can streamline this process. This guide demonstrates how to integrate VAT validation in Go using EuroValidate's API, taking you through step-by-step setup and execution.

Introduction

Value Added Tax (VAT) validation is essential for companies operating in Europe, ensuring compliance and correct tax calculations. EuroValidate provides a straightforward API for developers to verify VAT numbers programmatically. This guide is tailored for backend developers using Go (Golang), focusing on simplicity, performance, and reliability.

Prerequisites and Setup

To follow along with this guide, ensure you have the following:

  • Go version 1.15 or later
  • Access to EuroValidate API credentials
  • Essential Go packages (net/http, encoding/json)

Getting an API Key

  1. Sign up at EuroValidate to get a free API key.
  2. Follow the instructions in your dashboard to find your API credentials.

Understanding the VAT Validation API

EuroValidate's VAT validation endpoint provides detailed insights into any VAT number. For this example, we will use the endpoint:

  • GET /v1/vat/{number}

Key Parameters

  • vat_number: The VAT number to validate.
  • country_code: ISO country code of the VAT number.

Full Example: Validate VAT in Go

Let's dive into creating a Go application that validates VAT numbers.

Step 1: Setting up the Go Environment

First, initialize your Go module and import necessary packages:

// go.mod
module vatvalidation

go 1.16
Enter fullscreen mode Exit fullscreen mode
// main.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"
)

// VATResponse holds the response structure from the API
type VATResponse struct {
    VATNumber    string `json:"vat_number"`
    CountryCode  string `json:"country_code"`
    Status       string `json:"status"`
    CompanyName  string `json:"company_name"`
    CompanyAddress string `json:"company_address"`
    RequestID    string `json:"request_id"`
    Meta         struct {
        Confidence      float64 `json:"confidence"`
        Source          string  `json:"source"`
        Cached          bool    `json:"cached"`
        ResponseTimeMS  int     `json:"response_time_ms"`
    } `json:"meta"`
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Crafting the API Request

Build the HTTP request that interacts with the VAT validation endpoint:

func validateVAT(vatNumber string) (*VATResponse, error) {
    url := fmt.Sprintf("https://api.eurovalidate.com/v1/vat/%s", vatNumber)
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return nil, err
    }
    req.Header.Add("Authorization", "Bearer YOUR_API_KEY")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var vatResponse VATResponse
    if err := json.NewDecoder(resp.Body).Decode(&vatResponse); err != nil {
        return nil, err
    }

    return &vatResponse, nil
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Handling API Responses

Analyze the JSON response, handling potential errors:

func main() {
    vatNumber := "NL820646660B01" // Example VAT number

    response, err := validateVAT(vatNumber)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(1)
    }

    fmt.Printf("VAT Number: %s\n", response.VATNumber)
    fmt.Printf("Status: %s\n", response.Status)
    fmt.Printf("Company: %s\n", response.CompanyName)
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Validating and Processing VAT Data

Utilize the parsed data in your application logic to ensure VAT compliance and logging.

Code Walkthrough and Explanation

This section dives deeper into each part of the Go code:

  1. Go Module Initialization: Ensures modular code management.
  2. HTTP Request Construction: Utilizes net/http package for making requests with headers.
  3. JSON Response Parsing: Efficiently decodes JSON using Go's standard library.
  4. Error Handling: Implements error-checking at each critical step to handle API failures gracefully.

Testing and Debugging

Testing Locally

  • Use valid test numbers like FR40303265045 and observe valid responses.
  • Handle invalid responses when using numbers like DE89370400440532013000.

Common Pitfalls

  • Ensure your API key is correctly set in the authorization header.
  • Check your network connection for latency issues; the average response time is under 150ms.

Conclusion and Next Steps

Integrating VAT validation using Go and EuroValidate API enhances data accuracy and compliance. This baseline can be customized for broader tax integration needs. For more detailed documentation, visit the EuroValidate API Docs.

Call-To-Action

Get started by signing up for a free API key at EuroValidate. Explore more advanced features with SDKs and further API documentation.

Start validating VAT in your application today!

Top comments (0)