Fussy Developer’s Five-Minute Miracle with Minimal APIs

It had been a long day for Fussy Farid. True to his name, everything seemed to annoy him—from the slow response of his code editor to the last-minute change requests in the client meeting. The world, it seemed, was out to test his patience.

Just as the clock was inching toward the end of the day, his manager popped in with a cheerful tone that Farid knew he couldn’t trust.

“Hey Farid, remember that new microservice product catalog we discussed? The client wants to see a quick demo. The front end is ready; we just need some quick APIs. Nothing fancy, just something functional by the end of the day. Thanks, buddy!” And with that, the manager disappeared before Farid could even protest.

Farid slumped in his chair, groaning. “Quick APIs? By the end of the day? Is this some kind of joke?”

Enter Happy Hena, the ray of sunshine in the team. Always cheerful and brimming with solutions, Hena noticed Farid’s despair from across the room.

“Farid, what’s wrong now?” she asked, her voice as light as a summer breeze.

Farid sighed dramatically. “The boss wants me to create sample APIs for a demo, and I’ve got, what? A couple of hours left? There’s no way I can do this. I’ll need to create controllers, models, services… It’ll take forever! Goodbye, dinner plans.”

Hena couldn’t help but laugh. “Oh, come on, Farid. Don’t tell me you haven’t heard of Minimal APIs. They were introduced in .NET 6 and got even better in .NET 8!”

“Minimal what now?” Farid shot her a look of disbelief. “Another thing to learn? I don’t have time for this!”

“Relax, brother,” Hena said, waving her hand dismissively. “Minimal APIs are super easy. You can have this done in five minutes.”

Farid narrowed his eyes. “Five minutes? You’re joking, right?”

“Of course not!” Hena grinned. “Let me show you.”

She pulled up a chair next to Farid and opened her laptop. “Okay, Farid, prepare to have your mind blown.”

Farid crossed his arms. “This better not turn into a one-hour YouTube tutorial. Those always make me fall asleep.”

Hena laughed. “Nope, just code. Watch this.”

She opened Visual Studio and started typing.

“First, we initialize the app,” she explained. “No need for controllers or heavy setup. Just this:”

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();        

Farid raised an eyebrow. “That’s it? No Startup.cs? No magic rituals?”

“Exactly! Minimal APIs are minimal, Farid. Stay with me.” She kept typing.

“Next, we define some dummy products. No database setup needed for the demo.”

var products = new List<Product>
{
    new Product { Id = 1, Name = "Laptop", Price = 1200, Stock = 5 },
    new Product { Id = 2, Name = "Smartphone", Price = 800, Stock = 10 },
    new Product { Id = 3, Name = "Headphones", Price = 150, Stock = 25 }
};        

Farid leaned in, intrigued. “Okay, not bad. But where’s the part where we summon APIs?”

Hena smirked. “Coming up. Now, we map our API endpoints directly, like this.”

She typed:

app.MapGet("/products", () => Results.Ok(products));        

Farid’s jaw dropped. “Wait, that’s it? No controllers, no services?”

“Yup,” Hena said smugly. “And let’s add another one to get a product by ID.”

app.MapGet("/products/{id:int}", (int id) =>
{
    var product = products.FirstOrDefault(p => p.Id == id);
    return product != null ? Results.Ok(product) : Results.NotFound("Product not     found.");
})        

Farid blinked. “You’re telling me… all this works without a ton of boilerplate code?”

Hena grinned. “Exactly! Oh, and if the client wants to search for products by name, we just do this:”

app.MapGet("/products/search/{name}", (string name) =>
{
var filteredProducts = products.Where(p => p.Name.Contains(name,                   StringComparison.OrdinalIgnoreCase)).ToList();
return filteredProducts.Any() ? Results.Ok(filteredProducts) : Results.NotFound("No products found.");
});        

Farid leaned back in his chair, looking both amazed and annoyed. “Why did no one tell me about this before? I’ve been doing API development the hard way for years!”

“Because you never listen,” Hena teased. “Now, let’s make it even cooler. Add Swagger to auto-generate the API docs.”

She added a few more lines:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

app.UseSwagger();
app.UseSwaggerUI();`        

Farid shook his head in disbelief. “So now the client gets APIs and documentation? You’re making me look bad, Hena. What are the names of the packages you just added?” "Farid," Hena said with a mock-serious face, "you don’t need me to look bad. You manage just fine on your own. And the packages are Microsoft.AspNetCore.OpenApi and Swashbuckle.AspNetCore”

Farid laughed, the tension finally easing. “Alright, alright. You win. But if this blows up during the demo, you’re taking the heat.” Deal,” Hena said, hitting F5 to run the app. She opened the browser to https://localhost:5000/swagger.

The Swagger UI loaded, showing all the API endpoints ready to test. Farid stared at the screen, speechless.

"Go ahead," Hena said, "try them out." Farid clicked on an endpoint, hit Try it out, and saw the API return the product data instantly. "This is… actually amazing. This is something I can make my 3 years old do too", Farid joked. “Welcome to the future, Farid,” Hena said, standing up and patting his shoulder. “Next time, teach your toddler this so they can handle office emergencies for you.”

Farid smirked. “If you teach her I am sure she can do that too.”

“Deal,” Hena said, walking away. “But next time, I’ll charge tea for every trick.”

“Deal,” Farid laughed.

The full code- Minimal APIs sample · GitHub

要查看或添加评论,请登录

社区洞察

其他会员也浏览了