🏦 Creating a Credit Analysis API with Azure Functions in Java
In this second article of our Azure Functions + Java series, you’ll build a real and functional API that simulates a credit analysis, receiving client data and returning whether the credit is approved based on a randomly generated score.
📌 Didn’t read the introduction yet? Start here:
👉 Azure Functions with Java: When to Use, Pros, Limitations, and Triggers
🚀 What Are We Building?
We’re going to create an HTTP-based Azure Function that:
- Receives a JSON payload with client name and desired amount
- Generates a random credit score (from 0 to 1000)
- Applies a rule: score ≥ 600 AND value ≤ 5000 = approved
- Returns a JSON response with the result
💼 This use case is useful for:
- Simulating a real-world credit scoring process
- Testing microservices and APIs
- Prototyping financial systems and flows
⚙️ Prerequisites
- Java 17+
- Maven
- Azure CLI
- Azure Function Core Tools
npm install -g azure-functions-core-tools@4 --unsafe-perm true
📁 Creating the Project
Open your terminal and navigate to a folder that is not empty (e.g., C:dev) and run:
mvn archetype:generate -DarchetypeGroupId=com.microsoft.azure -DarchetypeArtifactId=azure-functions-archetype -DgroupId=com.exemplo.fn -DartifactId=fn-analise-credito -Dversion=1.0-SNAPSHOT -Dpackage=com.exemplo.fn -DinteractiveMode=false -Darchetype.test=false
Tip: Do not run this command inside the destination folder (e.g., fn-analise-credito), or Maven will throw an error because it expects to create the folder from scratch.
🧹 Optional: Remove Unit Test Folder
By default, the generated project includes a src/test folder with a sample unit test. If you’re not using unit tests at this stage, you can delete it with the following command:
🪟 For Windows (CMD or PowerShell):
Remove-Item -Recurse -Force .srctest
🐧 For Linux or macOS:
rm -rf fn-analise-credito/src/test
💡 You can run this right after generating the project. It helps to keep the structure clean for simple proof-of-concept scenarios.
✍️ Coding the Credit Analysis Function
🔧 File: Function.java
package com.exemplo.fn;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.util.Optional;
import java.util.Random;
/**
* Azure Function that simulates a credit analysis.
*/
public class Function {
@FunctionName("analiseCredito")
public HttpResponseMessage run(
@HttpTrigger(name = "req", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
String body = request.getBody().orElse("");
if (!body.contains("nome") || !body.contains("valor")) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Missing required fields: 'nome' and 'valor'")
.build();
}
String nome = extractValue(body, "nome");
double valor = Double.parseDouble(extractValue(body, "valor").replace(",", "."));
int score = new Random().nextInt(1001); // 0 to 1000
boolean aprovado = score >= 600 && valor <= 5000;
String responseJson = String.format(
"{ "cliente": "%s", "valor": %.2f, "score": %d, "aprovado": %s }",
nome, valor, score, aprovado
);
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(responseJson)
.build();
}
private String extractValue(String json, String key) {
String[] parts = json.replace(""", "").replace("{", "").replace("}", "").split(",");
for (String part : parts) {
if (part.trim().startsWith(key)) {
return part.split(":")[1].trim();
}
}
return "";
}
}
📥 Example Request & Response
✅ Sample Input
{
"nome": "Leandro",
"valor": 3000
}
✅ Sample Response
{
"cliente": "Leandro",
"valor": 3000.00,
"score": 712,
"aprovado": true
}
▶️ Testing Locally
Compile and run the function:
mvn clean package
mvn azure-functions:run
Send a test request using Postman or curl:
curl -X POST "http://localhost:7071/api/analiseCredito" -H "Content-Type: application/json" -d "{ "nome": "Leandro", "valor": 3000 }"
You should receive a response with score and approval decision.
✅ Final Thoughts
In this article, you created a real-world Azure Function that:
- Parses and validates JSON input
- Applies business logic (credit score simulation)
- Returns a formatted and dynamic JSON response
This is a solid foundation for building:
- APIs
- Cloud-native services
- Event-driven systems
The full code and instructions are available on GitHub:
👉 leandrofmarcos/fn-credit-analysis-java
📚 Next in the Series
We’ll continue exploring Azure Functions with more real use cases using Java:
- ✅ Simulating Credit Analysis with Azure Functions in Java
- 🔜 Queue Trigger: Processing Tasks Asynchronously with Java
- 🔜 Blob Trigger: File Handling in Azure Storage
- 🔜 Durable Functions with Java: Orchestrating Workflows Serverlessly
- 🔜 Logging and Monitoring with Application Insights
- 🔜 Best Practices for Scalable and Maintainable Functions
❤️ Enjoyed This?
Leave a ❤️, drop a comment, or share this with your team or community.
Let’s show the world that Java and Azure Functions are a powerful combo in modern serverless architectures! 💻☁️