π¦ 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 .\src\test
π§ 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! π»βοΈ
Top comments (0)