Coding Clean, Reliable, and Safe REST APIs with ASP.NET Core 8 1st Edition Anthony Giretti - Download the ebook in PDF with all chapters to read anytime
Coding Clean, Reliable, and Safe REST APIs with ASP.NET Core 8 1st Edition Anthony Giretti - Download the ebook in PDF with all chapters to read anytime
https://ebookmass.com/product/architecting-asp-net-core-applications-
carl-hugo-marcotte/
ASP.NET 8 Best Practices 1 / converted Edition Jonathan R.
Danylko
https://ebookmass.com/product/asp-net-8-best-practices-1-converted-
edition-jonathan-r-danylko/
https://ebookmass.com/product/geometric-patterns-with-creative-coding-
coding-for-the-arts-1st-edition-selcuk-artut/
https://ebookmass.com/product/geometric-patterns-with-creative-
coding-1st-edition-selcuk-artut/
https://ebookmass.com/product/pro-asp-net-core-3-develop-cloud-ready-
web-applications-using-mvc-blazor-and-razor-pages/
https://ebookmass.com/product/saving-finley-military-hero-heroine-
romance-safe-and-secure-book-8-alyssa-bailey/
Coding Clean,
Reliable, and Safe
REST APIs with
ASP.NET Core 8
Develop Robust Minimal
APIs with .NET 8
Anthony Giretti
Coding Clean, Reliable, and Safe REST APIs with ASP.NET Core 8:
Develop Robust Minimal APIs with .NET 8
Anthony Giretti
La Salle, QC, Canada
Acknowledgments�����������������������������������������������������������������������������xiii
Prerequisites��������������������������������������������������������������������������������������xv
Introduction��������������������������������������������������������������������������������������xvii
iii
Table of Contents
iv
Table of Contents
Uploading Files��������������������������������������������������������������������������������������������155
Streaming Content��������������������������������������������������������������������������������������������169
Handling CORS��������������������������������������������������������������������������������������������������171
API Versioning���������������������������������������������������������������������������������������������������177
Versioning by Headers���������������������������������������������������������������������������������178
Versioning by Route�������������������������������������������������������������������������������������187
Documenting APIs���������������������������������������������������������������������������������������������190
Managing API Versions in Swagger�������������������������������������������������������������192
Adding Comments on Endpoints�����������������������������������������������������������������199
Grouping Endpoints by Tag��������������������������������������������������������������������������206
Other Customizations����������������������������������������������������������������������������������207
Summary����������������������������������������������������������������������������������������������������������212
v
Table of Contents
vi
Table of Contents
Index�������������������������������������������������������������������������������������������������419
vii
About the Author
Anthony Giretti is a senior developer/architect
at Marchex in Toronto, Canada. He appreciates
learning and teaching new technologies and
has a knack for web technologies (more than
17 years’ experience) and a keen interest in
.NET. His expertise in development and IT and
his passion for sharing his knowledge allow
him to deconstruct any web project in order
to help other developers achieve their project
goals. He loves to deal with performance constraints, high availability,
and optimization challenges. Anthony is the author of Beginning gRPC
with ASP.NET Core 6 (Apress), a six-time Microsoft MVP, and a Microsoft
Certified Software Developer (MCSD).
ix
About the Technical Reviewer
Fiodar Sazanavets is a Microsoft MVP and a
senior software engineer with over a decade
of professional experience. He primarily
specializes in .NET and Microsoft stack and
is enthusiastic about creating well-crafted
software that fully meets business needs.
He enjoys teaching aspiring developers and
sharing his knowledge with the community,
which he has done both as a volunteer and
commercially. Fiodar has created several
online courses, written a number of technical books, and authored other
types of educational content. He also provides live mentoring services,
both to groups and individuals. Throughout his career, he has built
software of various types and various levels of complexity in multiple
industries. This includes a passenger information management system
for a railway, distributed smart clusters of IoT devices, ecommerce
systems, financial transaction processing systems, and more. He has also
successfully led and mentored teams of software developers.
xi
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
Acknowledgments
Completing this book could not have been possible without the
participation and assistance of many people, and I would like to express
my special thanks to them. First, thanks to my wife, Nadege, who never
stopped supporting me. I love you!
Next, I would like to thank the rest of my family for their support.
This book has been written in special conditions since I was
hospitalized for a severe disease that could have taken my life. I haven’t
given up, and I hope this book will please you; if I have completed it, it’s for
a good reason, I hope!
I also would like to thank my colleagues at Marchex, especially
my friend (and colleague) Callon Campbell, who never stopped
encouraging me.
Thanks to my friend Dominique St-Amand, who has never been stingy
with comments to help me improve this book.
Last but not least, Fiodar Sazanavets! Thanks, my friend, for being part
of this journey; you were essential in this new challenge I set for myself.
Without you, I wouldn’t have succeeded.
xiii
Prerequisites
This book is aimed at beginner and intermediate developers who want to
take their Application Programming Interface (API) development skills to
the next level. In this book, I assume you know the basics of .NET, C#, and,
therefore, the fundamentals of Object-Oriented Programming (OOP). I
also assume you’ve already used Visual Studio and know how to use it. As
for web fundamentals, I’ve started from scratch, so if you don’t know much
about the Web, no problem!
xv
Introduction
Dear reader friend, welcome to this book!
In my career, I have worked in various companies and on various
complex APIs. Although each company had its challenges, I can assure you
that they all had one thing in common: their APIs lacked a lot of love and
care. They all suffered from the same problems: poor code organization
due to an accumulation of minor errors over the years, lack of consistency
in the definition of coding conventions, lack of technological refreshment,
misinterpretations of the HyperText Transfer Protocol (HTTP) and
Representational State Transfer (REST) principles, missing logging or bad
logging practice, and not enough care regarding performances.
I have always enjoyed helping teams overcome these difficulties,
and I have decided to write a book to share my experiences and guide
you through the best practices of API implementations. This book will
focus on some technical architecture of an API, but it will focus more on
coding practices to help you avoid the most common mistakes in your
development career. I will not cover solution architecture where an API
is built around other systems, but keep assured; I will show you how to
implement access to external data sources.
At the end of this book, you will know how to develop APIs with ASP.
NET Core 8 properly coded, performant, resilient, secure, testable, and
debuggable. You will go from a beginner/intermediate level to a senior
level by learning precisely WHAT you need to know without feeling
overwhelmed by a ton of information.
Let’s go!
xvii
CHAPTER 1
Introducing HTTP
and REST
Before we dive into ASP.NET Core 8 and API development, let’s first go
back to the basics of any web application. Whether a website is run from a
browser or a web service (web API), it’s always the same principle: a client
and a server will communicate together; a client will send a request to a
server, which will then respond to the client. This is all possible with the
magic of the HTTP communication protocol. Under this protocol, data
can be transported using different formats and constraints. Here is REST!
REST is an architectural concept of data representation. Of course, these
two should not be confused. In this chapter, we will cover the following
content:
• HTTP
Note In this book, I will often refer to RFCs. The reason is that I
want to teach you the good practices for using HTTP. However, in
practice, the actual implementation of those RFCs may differ. Finally,
while this chapter aims to teach you the good techniques with HTTP,
I will not cover all the HTTP capabilities. I’ll stick to what you need to
know about building clean APIs with ASP.NET Core.
There are also different versions of HTTP. HTTP has evolved. I will not
go into details; in the following, you can find the published versions of the
protocol:
• HTTP/0.9 (obsolete)
• HTTP/1.0 (obsolete)
2
Chapter 1 Introducing HTTP and REST
3
Chapter 1 Introducing HTTP and REST
These characteristics may seem abstract, but they will become more
apparent as we read this book together. In the next section, I will give
you an overview of HTTP requests and responses. This will help you
understand HTTP before going into detail.
4
Chapter 1 Introducing HTTP and REST
In the following section, I will detail the HTTP verbs, the request
headers, the format of a URI, the different parameters passed in a
request, the HTTP status codes, the response headers, and the payload
formats returned to the client. Once we finish those points, I will bonify
Figure 1-1 with more details.
HTTP Implementation
Let’s dive into more detail to see what HTTP verbs, request headers,
response headers, and HTTP status codes are and how the client passes its
parameters in HTTP requests combined with the invocation of a URI.
5
Chapter 1 Introducing HTTP and REST
HTTP Verbs
RFC 7231 defines the following verbs:
6
Chapter 1 Introducing HTTP and REST
7
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
Other documents randomly have
different content
Naida received me very graciously on the following afternoon. I was
a little surprised that she had made no attempt whatever to alter her
surroundings or in any way to create an atmosphere. The ordinary
hotel furniture and hangings were lightened only by a profusion of
flowers, mostly deep red roses. In place of the flowing robes one
might have expected, the great dancer wore a severe tailor-made
costume of grey tweed. Her hair was brushed plainly back from her
forehead and tied with ribbon behind. There was no other caller
present when I arrived.
"It would be charming of you to come so soon," she murmured, as
she held out her hand, "if it were your own will which brought you."
"My own will would have brought me here in any case," I assured
her, "but as it happens I have another mission. I am to ask you what
has become of Felix Worth."
I looked into the eyes of another woman for a moment, and I was
afraid. Her momentary fit of fury, however, passed. She motioned
me to a chair.
"How much do you know of this matter?" she asked.
"Nothing at all," I answered promptly.
"That is the way with him," she ruminated. "His agents never know
anything."
"That does not, I trust, prevent my finding great pleasure in making
your acquaintance, Mademoiselle," I ventured.
She looked at me curiously. Sixty seconds ago I should have
described her as being, off the stage, disappointedly plain. I realised
my mistake.
"It does not prevent your paying me any compliments you choose,"
she replied. "There is no reason why we should not be friends—even
comrades. The only cloud between us appears to be that it will fall
to your lot to kill the only man I have ever really cared for."
I started in my chair.
"I can assure you," I told her, "I am not out for that sort of thing at
all."
"But it will come," she persisted.
"It will not," I contradicted her firmly. "I have done all the killing I
want to, in fair fighting. I have a weakness for adventures, but
nothing would induce me to become an assassin."
She looked at me contemplatively, leaning across from her chair with
her chin balanced upon her hands. Then she got up and brought me
a queer round wooden box of fragrant Russian cigarettes. She
herself lit one, and I followed her example.
"Are you afraid, dear earnest Englishman," she asked, "that I should
hate you? Let me tell you the truth. For this man I have no love any
more. And he must die."
"He may live or he may die," I answered, "but I am no man's
executioner."
"We shall see," she remarked indifferently. "You are a just man,
beyond a doubt, but I like you. You are different from all others."
"In what respect?" I enquired.
"I admit you here," she replied, "to the intimacy of a private visit,
yet you have not yet suggested that you should become my lover. It
intrigues me, this diffidence."
I felt a sudden desire to get out of the room. She laughed at me,
laughed with simple, unaffected mirth, laughed till she came over
and laid her hands upon my shoulders.
"Go away, dear man," she begged, "before I make myself foolish
about you. You shall sit at my side to-night, and perhaps then, when
you see what others think of me, you may whisper different things."
"And where do I sit by your side to-night?" I asked.
"You and your two friends," she said, "sup with me in the restaurant
downstairs at midnight. Convey my compliments and this invitation
to your charming lady companion. I shall see her at the theatre and
will confirm it."
She gave me her fingers and held them for a moment against my
lips. Then I went out, a little dazed.
I began to fear that Naida was going to make trouble for me. At the
theatre that evening she demanded my constant attendance. Twice
she sent notes to my dressing room, and in the midst of the
tumultuous applause which followed her wonderful dancing, when
she stood in the wings with us after her seventh recall, she tore one
of the red roses which had been thrown on to the stage from its
cluster, and thrust it in my buttonhole.
"So!" she whispered. "They will know from whom that rose comes.
Your fingers will caress it when you sing. They will applaud you the
more for my sake."
This was all very pretty and soothing to my vanity, and, I frankly
admit, in its way pleasant, but I had all the time the feeling that it
was likely to bring trouble upon me. When, in her most charming
manner, Naida had issued her invitation to Rose, her enthusiastic
acceptance was entirely marred for me by the manner of it.
"A supper party will be perfectly delightful," Rose declared, smiling
with dangerous sweetness. "I have a little headache to-night but
that will pass. In any case you will not mind if Leonard—if Mr. Cotton
should bring me away early."
"So long as you do not rob me of my dear cavalier," Naida replied, to
my dismay, squeezing my arm.
I marched Leonard on one side, taking advantage of the insistent
roars of recall which drew Naida back on to the stage.
"Look here, Len," I said, "I don't know what this game is, but I'm
playing it for the three of us. I am obeying orders so far as
Mademoiselle Naida is concerned. If Rose won't see it, I shall rely
upon you."
"I'll do my best, old chap," he promised, with a gloom which I
fancied was not altogether natural. "It's a jolly hard situation,
though. Rose had asked me to take her out to supper to-night, and
to dinner on Sunday night."
"You can count that dinner off," I said firmly. "We three have dined
together every Sunday night since we started out. Sometimes it's
been a scrag of mutton and a glass of beer; once or twice—that
week at Cromer, Len—not even that. On Sunday night it's going to
be caviare and a Maryland chicken, and I'm in it."
"That's all right," Leonard assured me. "Of course, Rose thought that
you'd be in attendance on Naida."
"You and I won't have any misunderstanding, at any rate, Len," I
insisted. "Naida means just as much to me as that bit of fluff on your
coat. When our year is up, I shall ask Rose to marry me, and though
you're the dearest fellow in the world, I hope she'll have me and not
you."
"I sha'n't take advantage, old chap," Leonard promised, with a sigh,
"but it's getting filthily difficult. She pretended she wanted me to kiss
her last night."
"I'll punch your head if you do," I answered savagely. "Our call."
The supper party did not improve matters. We found quite a
distinguished little gathering in the foyer of the Milan, including the
managing director of the Parthenon, some of the best known
dramatic critics, a famous actor and his wife, another and a lady
who might have been, a foreign ambassador, and two other well-
known and distinguished men about town. Naida did her duty by
placing a very distinguished nobleman with cosmopolitan tastes
upon her right, but, to my secret dismay and the wonder of the rest
of the company, she insisted upon my occupying the seat on the
other side of her.
"Now," she whispered, looking at me from under her eyelashes with
that slow, curious smile upon her lips, "I have made the little lady
jealous, is it not so? And also the great managing director who pays
me my salary, and perhaps others. But what does it matter? You are
content?"
The lie came uneasily from my lips. Naida, however, seemed
satisfied. It was borne in upon me now that it was her deliberate
purpose, part of the game, in fact, not only to exploit me as a victim
of her charms but to practically advertise her simulated infatuation. I
watched Rose flirting desperately with a very attractive man who
was seated upon her left, and for a moment I felt that the situation
was impossible—that I should do best to mutter a few plain words to
my hostess and deliberately dissociate myself from the rôle into
which I had drifted. Then I remembered our chief's confidence—
Naida spoke to me with unexpected kindness. I caught the echo of
Rose's unnecessarily joyous laughter, and I changed my mind.
Thenceforth I played my part. I lent myself to the gaiety of the
moment. We were all young together. The wine was good, life was
good, the very music seemed playing us down the avenues of
pleasure. From a gay party we became almost an uproarious one.
We moved outside into the lounge for our coffee, Naida never letting
me for an instant leave her side, relegating to me the duties of host,
thrusting her pocketbook into my hand, insisting that I should order
the cigars and liqueurs, fee the waiters, and even sign the bill on her
behalf. There were many smiles amongst the little company, shrugs
of the shoulders, and whispered enquiries as to my identity. My
fictitious position seemed to make me an object of envy, but I never
altogether lost my head. I waited for my opportunity, and when it
came I rose quickly to my feet and walked over to Rose's side. Her
companion of the moment had been summoned away to speak to
some acquaintances in another part of the lounge.
"Rose," I began sternly——
She looked at me with a bright but artificial smile. I leaned down
and continued under my breath.
"I play the buffoon to order," I reminded her. "You, too, have your
part in this."
"Indeed?" she murmured.
"Yes! Your part is not to make mine more difficult. Your part is to
remember——"
Then I stopped short. It was a difficult position. There was my
contract with Leonard to be borne in mind.
"To remember what?" she asked, looking at me more naturally.
"The things of which your heart assures you," I answered. "I am
only human. If I fail to-night, the fault will not be wholly mine."
After that there was a change in Rose's demeanour, and once, when
our eyes met, she smiled. Naida, however, still played her part of
sorceress. She seemed impatient of every word she was forced to
speak to others. She whispered often in my ear. Even her fingers
sought mine. It was just at this stage that for the first time I noticed
the somewhat singular appearance of a man who was watching us
from the few seats upstairs reserved for guests of the hotel who
were not in evening dress. As though he sought concealment, he
had found a chair in the most remote corner and was half hidden by
a slight projection of the wall. He had a mass of black hair, a heavy,
sallow face, from which one formed the idea that he had recently
removed a beard, and dark staring eyes. He was untidily dressed for
his surroundings, amongst which he seemed curiously out of place.
An impulse prompted me to point him out to Naida. She glanced in
the direction I indicated but merely shrugged her shoulders.
"Dear friend," she whispered, "you forget that I am a famous
person, more so abroad than in your little island. There are many
who watch me with thoughts in their heart which they will never
dare to utter. There are many who would give a share of their
possessions to be seated where you are seated, to be treated as I
am treating you."
"The man is a foreigner, without a doubt," I remarked.
"And foreigners," she answered, with a stabbing little glance, "are
quicker to feel and understand than Englishmen."
We kept the party going until long past closing time, and then an
adjournment of our diminished numbers was made to Naida's suite.
Here she distributed signed photographs to her remaining guests,
accompanied by a wave of the hand which meant dismissal. Rose
and Leonard were amongst the first to leave, Rose with a look in her
eyes which might have meant anything. I stepped quickly forward.
Naida looked at me warningly. Now that we had left the lounge, it
seemed to me that her demeanour had to some extent changed.
"For your impatience, Monsieur Maurice," she said, "you will be the
last. Offer the cigarettes, if you please. And your friend Mr. Cotton,
will he not take a whisky and soda before he goes?"
One by one they drifted away. Rose and Leonard were driven home
by one of the former's new admirers. The time came when we were
alone. Naida listened to the closing of the door and to the clanging
of the lift gate. Then with her back to the table against which she
was leaning, she looked across at me with an odd little smile upon
her lips.
"So we are alone, my friend."
"It has that appearance," I admitted, taking one of her cigarettes
and lighting it. "I await your further instructions."
She nodded her head slowly. She seemed to be considering my
attitude.
"My further instructions," she mimicked. "Oh, Monsieur Maurice,
what a strange person! Ring the bell on your left, please."
I obeyed. A maid presented herself at once from the inner room.
Naida spoke to her for a moment in some weird language. Then she
turned towards me, yawned and stretched herself.
"Prepare for a shock," she said. "For ten minutes I leave you. You
seat yourself in that easy chair, you take a whisky and soda and the
evening paper, you make yourself at home. You understand?"
"Perfectly," I answered, not at all sorry for a few minutes' solitude.
"Then au revoir! But have no fear," she added, looking back with a
mocking smile, "I shall return."
A quarter of an hour or so passed. I heard Naida telephoning from
her bedroom and heard her voice in conversation with her maid.
Then she reappeared. She was wearing a yellow creation tied
around her with a girdle, Chinese sandals tied with broad yellow
ribbon; and her unloosed hair was gathered together with ribbon of
the same colour. She displayed herself for my admiration.
"You admire, Monsieur Maurice? You like the colour?"
"You look charming," I replied. "And now?"
She held up her finger.
"You are not to stir," she directed, waving her finger at me.
She moved towards the door which led into the corridor, opened it
softly and peered outside. Then, as though not satisfied, she
disappeared altogether. When she returned, she closed the door with
a little slam and threw herself into a chair opposite to me.
"And now?" I repeated patiently.
"It is the hardest part of your task, this, Monsieur Maurice," she said,
with a demure little droop of the eyes. "You see the time? It is
exactly two o'clock. For one hour you remain where you are. At the
end of that hour you are free. You may then leave, and, if you wish
it so, your courtship of Naida is over."
"And for that hour?" I asked, a little unsteadily.
She came and sat on the arm of my chair. Her face was upturned to
mine.
"Shall I keep you company?" she whispered.
I leaned down and took the kiss she offered me. I held her for a
moment in my arms. Then I gripped her wrists.
"Naida," I said, and my own voice sounded to me unfamiliar, "of
course I know this is a game, but I don't understand the rules."
"We make them," she murmured.
"I am in love with Rose Mindel," I continued. "I should be married to
her at the present moment but for a stupid agreement between
Leonard Cotton and myself, made when we three started out
together. I am in love with her, but I'm no Joseph. You know what
you are, and your power. I'm not any different from other men."
"But you do not care, then?" she asked quickly.
"There isn't any ordinary young man of my type," I answered, "who
has drunk your wine and sat by your side all the evening, and
received your kindness, and finds himself here alone with you, who
wouldn't care—in a way—the wrong way. I care like that, if it's any
good. And now you understand."
She slipped from her place, kissed me on both eyes, and ran across
to the door of the inner room. She looked back at me only for a
moment, opened her lips, said nothing, and disappeared, closing the
door softly behind her. I mixed myself the stiffest whisky and soda I
had ever concocted in my life, lit a cigar from a box I found on the
sideboard, and sat down to watch the clock.
At five minutes to three, I was walking up and down the room with
my overcoat on. At a minute to the hour, as I stood with my eyes
glued to the clock, the inner door softly opened. Naida stood framed
upon the threshold. There was a look of distress upon her face.
"Monsieur Maurice," she said, "I had made up my mind to say
nothing, but that was wrong. You are a very honourable young man
and I have not met many. It has been promised to me that no harm
shall come to you, but yet—go warily to the lift."
She disappeared and closed the door. For the first time she locked it.
Somehow, I felt, as I stepped out into the corridor, that the dangers
which might be waiting for me were small things. I stood for several
seconds, looking up and down. To reach the lift I had to traverse the
whole of the corridor, turn to the left and pass along another shorter
one. I stepped out carelessly enough, and then—the scantily lit
passage seemed suddenly filled with whispering voices, with eyes
peering at me from mysterious corners; the soft carpets behind me
were reverberant with muffled and stealthy footsteps. I was acutely
conscious of the presence of danger. As I neared the corner of the
corridor every nerve of my body was bristling with apprehension.
Before I turned, I paused for a moment and looked behind. There
was only a single electric lamp burning, but I could see dimly along
the empty space to the end. There was no sign of any moving
figure, nor any sound. Then I turned the corner to find myself
suddenly seized in a pair of giant arms, the dull flicker of upraised
steel before my eyes, the sallow, brutelike face, the black, flaming
eyes of the man who had watched me from the lounge, within an
inch or two of me.
I had no chance to call out. My assailant's left hand was upon my
throat. I could see him gathering strength to drive that knife down
into my heart. My brain was perfectly active. I waited with tense
muscles for the terrible moment, meaning to fling myself on one side
in the hope that I might escape mortal injury from that first blow, at
any rate. And then I saw something loom up behind. I saw an arm
raised even higher than my captor's, and I heard the wickedest
sound in life—the crash of dull metal into a man's skull. The grasp
upon my throat was instantly relaxed, doors were thrown open along
the corridor, and I sank back into a momentary fit of
unconsciousness.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookmass.com