Full Download Web API Development for the Absolute Beginner: A Step-by-step Approach to Learning the Fundamentals of Web API Development with .NET 7 1st Edition Irina Dominte PDF DOCX
Full Download Web API Development for the Absolute Beginner: A Step-by-step Approach to Learning the Fundamentals of Web API Development with .NET 7 1st Edition Irina Dominte PDF DOCX
com
OR CLICK HERE
DOWLOAD NOW
https://ebookmass.com/product/kubernetes-fundamentals-a-step-by-step-
development-and-interview-guide-1st-edition-himanshu-agrawal/
ebookmass.com
https://ebookmass.com/product/kubernetes-fundamentals-a-step-by-step-
development-and-interview-guide-1st-edition-himanshu-agrawal-2/
ebookmass.com
https://ebookmass.com/product/earls-well-that-ends-well-jane-
ashford-2/
ebookmass.com
https://ebookmass.com/product/claimed-by-the-wolf-lord-an-enemies-to-
lovers-paranormal-romance-lunar-bride-book-3-skye-wilson/
ebookmass.com
https://ebookmass.com/product/crossed-skis-carol-carnac/
ebookmass.com
https://ebookmass.com/product/functional-assessment-and-program-
development-3rd-edition-ebook-pdf/
ebookmass.com
https://ebookmass.com/product/a-thousand-vermilion-stars-patricia-
logan/
ebookmass.com
Oxford IB Diploma Programme IB Mathematics: analysis and
approaches, Standard Level, Print and Enhanced Online
Course Book Pack (English B for Ib Diploma Programme) Paul
La Rondie
https://ebookmass.com/product/oxford-ib-diploma-programme-ib-
mathematics-analysis-and-approaches-standard-level-print-and-enhanced-
online-course-book-pack-english-b-for-ib-diploma-programme-paul-la-
rondie/
ebookmass.com
Web API
Development for
the Absolute
Beginner
A Step-by-step Approach to
Learning the Fundamentals of
Web API Development with .NET 7
—
Irina Dominte
Web API Development
for the Absolute
Beginner
A Step-by-step Approach
to Learning the Fundamentals
of Web API Development
with .NET 7
Irina Dominte
Web API Development for the Absolute Beginner: A Step-by-step Approach
to Learning the Fundamentals of Web API Development with .NET 7
Irina Dominte
Iasi, Romania
Acknowledgments�����������������������������������������������������������������������������xix
Introduction���������������������������������������������������������������������������������������xxi
v
Table of Contents
vi
Table of Contents
Status Codes�������������������������������������������������������������������������������������������������������43
1xx – Informational����������������������������������������������������������������������������������������43
2xx – Success�����������������������������������������������������������������������������������������������43
3xx – Redirects����������������������������������������������������������������������������������������������44
4xx – Client Errors�����������������������������������������������������������������������������������������44
5xx – Server Errors����������������������������������������������������������������������������������������46
Cookies���������������������������������������������������������������������������������������������������������������47
Summary������������������������������������������������������������������������������������������������������������49
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
Chapter 8: Routing����������������������������������������������������������������������������235
What Is a Route?�����������������������������������������������������������������������������������������������235
Route Templates������������������������������������������������������������������������������������������236
Route Segments������������������������������������������������������������������������������������������237
Route Parameters����������������������������������������������������������������������������������������239
Route Tokens�����������������������������������������������������������������������������������������������240
Route Values������������������������������������������������������������������������������������������������241
Convention-based Routing��������������������������������������������������������������������������������241
Attribute Routing�����������������������������������������������������������������������������������������������242
Route Template Precedence�����������������������������������������������������������������������������246
How to Customize Routing��������������������������������������������������������������������������������247
Route Constraints����������������������������������������������������������������������������������������������248
Creating a Custom Route Constraint�����������������������������������������������������������249
Available Constraints�����������������������������������������������������������������������������������252
Creating Hierarchical Routes����������������������������������������������������������������������������253
Summary����������������������������������������������������������������������������������������������������������260
Chapter 9: Middleware���������������������������������������������������������������������261
Middleware Usage Scenarios���������������������������������������������������������������������������264
Introducing Custom Middleware�����������������������������������������������������������������������265
Create Your Own Middleware to Add Headers��������������������������������������������������267
Making an Extension Method for Our Middleware��������������������������������������������268
Understanding the Security Headers We Added�����������������������������������������������271
X-Content-Type-Options������������������������������������������������������������������������������271
X-Frame-Options�����������������������������������������������������������������������������������������271
X-Permitted-Cross-Domain-Policies�����������������������������������������������������������272
X-XSS-Protection�����������������������������������������������������������������������������������������273
Summary����������������������������������������������������������������������������������������������������������274
xi
Table of Contents
xii
Table of Contents
xiii
Table of Contents
Index�������������������������������������������������������������������������������������������������403
xiv
About the Author
Irina Dominte(Scurtu) is an independent
consultant and trainer, international
speaker, software architect, Microsoft MVP
for developer technologies, and Microsoft
certified trainer (MCT) with a wealth of
experience. Having taught classes, workshops,
and presentations for over 2,000 hours, Irina is
passionate about coding and keeping abreast
of the latest trends and best practices in
software architecture and .NET.
Twice a year, for five months each time, Irina teaches .NET and
C# to aspiring software developers or people interested in software
development or seeking to expand their knowledge. She is an active
member of the community and has founded the DotNet Iasi User Group
and the dotnetdays.ro conference, where she connects with like-minded
developers who are eager to share their expertise and insights.
Irina is also a prolific blogger, and her website, https://irina.codes,
features a wealth of articles on various coding topics. She decided to write
this book after learning firsthand how much people struggle to grasp new
concepts without proper guidance.
xv
About the Technical Reviewer
Layla Porter is an experienced software
engineer and developer advocate specializing
in .NET technologies. She’s a Microsoft MVP,
GitHub Star, and Progress Ninja, and in 2021
she founded the #WomenOfDotNet Initiative.
Layla has spoken at developer conferences
all over Europe and North America and is a
YouTube content creator and streamer. She
spends her time hiking, reading urban fantasy,
playing video games with her husband, and
doting on her two miniature pinschers, Cookie
and Lily.
xvii
Acknowledgments
The completion of this book wouldn’t have been possible without the help
and support of many people.
First, I want to thank my husband, who supported me every step and
encouraged me. Second, my daughter, Ilinca, who luckily enjoyed going
to daycare so I could write this book, and my in-laws, who were there to
babysit when I needed them.
Furthermore, I would like to express my appreciation to all those who
took the time to review my manuscript and provide constructive feedback
that helped refine the content. Special recognition goes to my tech
reviewer, Layla Porter, and my friends, Maria Rusu, Andrei Diaconu, and
Alexandra Nechita.
Last, but not least, thanks to my former students Tatiana Ciurescu and
Cosmin Dumitru, who were brave enough to shift their careers into tech
and never stopped learning.
xix
Introduction
This book aims to provide you, the reader, with a step-by-step approach
to learning Web API development. We start by introducing basic concepts
related to the Web in general and end with more advanced topics like
testing an API.
Across the chapters, you will notice a lot of things that might be subject
to debate—like splitting the code into different libraries, using different
coding standards, or even writing code that requires more lines than I
would use in real life.
Everything I choose to use in this book in terms of coding conventions,
API architecture, libraries, and topics covered was tested and proved
successful over the last eight years. In my spare time, twice a month,
I teach .NET to people that come from totally different domains than
programming. The vast majority now work in IT, and I dare to think that I
made a small contribution to that by using this approach.
xxi
PART I
The Basics
CHAPTER 1
What Is an API?
The term API is very widely used in the information technology (IT)
industry, and sometimes its usage can be confusing. The term is an
acronym for “application programmable interface.”
This is in fact the interface that gives a person or a system the ability to
interact with a piece of hardware or software through the operations that
are exposed.
Think about an API as a remote control, controlling your TV. You
press buttons to change the channels back and forth. Something similar
happens with APIs. You call methods and endpoints, or set values to
properties that are exposed to control aspects of that system.
While regular web applications are intended for humans to interact
with, APIs are like web applications but don’t have buttons or cute layouts
to interact with. Their intent is to be consumed by different “users.” In this
case, the “user” of an API might be a system or a developer.
There are many types of APIs with different scopes and addressability,
and they can be found in different parts of the web, or offline on devices.
Categorizing APIs
Now, if we ask ourselves, “What other kinds of APIs exist?” we may not
have a simple answer. Categorizing an API is a difficult job because we
need to add context to it. Imagine we have a set of LEGO blocks we need
to categorize. We might split them by color, or maybe by size. The same
happens with APIs—we can find more than one way to categorize them. In
the next section, we will talk about a few types of APIs that I have found to
be the most common and important.
Types of APIs
Push/Stream APIs
Push/stream APIs are event driven and send real-time notifications to
clients. In most cases, a web server will “push” messages or notifications
to a web browser. The business domain where you find APIs of this
category involves messaging, chats, video, streaming, or payments. There
is a significant chance of finding such APIs where time and real-time
processing are paramount.
Underneath, these APIs sometimes use protocols like WebSockets or
technologies like SignalR.
4
Chapter 1 Introducing Web API
Native APIs
APIs that are native usually are the interface of a device or a tool, allowing
us to interact with the device or tool. For example, web browsers have
a JavaScript API embedded that allows them to interpret and execute
the JavaScript code used in web applications. The same JavaScript API
will allow us to write and execute code directly in the Console tab of
developer tools.
In a similar manner, we can access our smartphone’s camera or
accelerometer through the exposed native API.
SDKs
An SDK, or software development kit, is a package of tools written in
different languages that helps developers build applications on top of that
package. For example, the .NET SDK provides a set of libraries and tools
that can be used by developers to build their own APIs or web applications.
SDKs get delivered as installers or as part of an Integrated Development
Environment workload and sometimes give you scaffolding capabilities
through those IDEs.
REST
REST, or representational state transfer, is an architectural style in the API
world that comes with a set of principles and guidelines about how to
design your API and leverage the underlying protocol in the correct way.
5
Chapter 1 Introducing Web API
REST was first mentioned by Roy Fielding in his dissertation thesis in 20001.
Since then, it has gained a lot of traction in the IT industry, but some
concepts were misunderstood.
Most of the APIs you will encounter in the web world are written in this
way. Not all respect the REST guidelines as they should, and are in fact JSON
over HTTP, but this is another subject that we will tackle at the right moment.
We will talk more about REST in a dedicated chapter.
RPC APIs
RPC is a term that means “remote procedure call,” and it has been
around for a while now in various forms. This model will look like you
are calling methods from the same application and using classes from
within the same scope or solution, but in fact the methods are hosted on a
different machine over the network. One of its main purposes is to make a
distributed system look and behave like a monolith.
If we look at Listing 1-1, the method calls seem to be part of the same
system, due to how an RPC API looks like. The calls to CreateOrder() and
ProcessPaymentFor() are actually calls over the network boundaries, even
if the look and feel for developers are local.
1
https://resources.sei.cmu.edu/asset_files/WhitePaper/2017_019_001_
505040.pdf
6
Chapter 1 Introducing Web API
7
Chapter 1 Introducing Web API
In the example that follows, you can see an HTML Tag Helper that
when executed generates an HTML input tag:
@Html.TextBoxFor(x=>x.AddedDate)
We can say that these application models are like self-contained boxes,
as shown in Figure 1-1.
The ASP Razor Pages application model comes with a nice structure, as
shown in Figure 1-2, and is very easy to understand and work with.
8
Chapter 1 Introducing Web API
Listing 1-2 and Listing 1-3 explore how a page would look in this
application model. We should have such source code file pairs for each
page we add to our application.
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about
<a href="https://docs.microsoft.com/aspnet/core">building Web
apps with ASP.NET Core</a>.</p>
</div>
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApplication1.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
9
Chapter 1 Introducing Web API
}
10
Chapter 1 Introducing Web API
To be honest, I enjoy writing such apps from time to time, and I rely
on them every time I have the opportunity. To me, it is faster and easier
to use something that is utterly familiar than to, let’s say, set up a React or
Angular frontend app and back it up with a standalone API. Nowadays,
ASP.NET MVC and ASP.NET Razor Pages or Blazor, are modern, easy to
learn, and have a wide addressability—meaning that they will do what they
are supposed to do in most cases.
These frameworks have a very well-defined place in the software
ecosystem, and they will be used in the future too. Now, most of the
enterprise world is more focused on non-functional requirements like
scalability, fault-tolerance, maintainability, and extensibility. These
requirements go beyond features and functionality to implement. These
applications tend to follow different architectures. They have a clear,
strict separation of frontend and backend, as shown in Figure 1-4, due to
different business needs.
11
Chapter 1 Introducing Web API
However, the same online shop could have a reporting section that an
admin might use once per month; it would be a waste of money to scale it.
Splitting the frontend code and the backend code into separate apps
is common practice. This way you will have a frontend app, and an API
or maybe several APIs that will send data to the frontend, as shown in
Figure 1-5. With this separation, we have the luxury of treating different
parts of a system independently in a way that might bring benefits to the
business.
12
Chapter 1 Introducing Web API
• You can scale only the part of your app that needs
scaling.
13
Chapter 1 Introducing Web API
Having this workload installed will allow us to start our code from a
predefined structure, as shown in Figure 1-7.
14
Chapter 1 Introducing Web API
If we run this project, we will see the web browser opening, and the
API will just work with dummy data, without us doing any configuration
at all. It will load the documentation page that comes by default in the
project template, and you’ll see something like Figure 1-8, with the small
exception that for you, the port might be different than 7038.
15
Chapter 1 Introducing Web API
16
Chapter 1 Introducing Web API
These APIs can serve as backends for native mobile applications or as web
frontends. They can even be consumed by other backends in point-to-
point communication patterns.
There are cases where you will need to make server-to-server requests
to implement functionality, and WEB API has classes that allow you to
do that.
For example, to process a payment using a payment provider, or to log
in a user using Facebook or Google, you might need to interact with their
APIs and make an API request from your API.
There are plenty of scenarios where someone might use a third-party
API to bring value to a product or a business, or to simply avoid reinventing
the wheel.
17
Chapter 1 Introducing Web API
Summary
In this chapter, we learned that an API is like a web app that doesn’t have
a presentation layer and responds only with data in the response body.
This data can have different formats, like JSON, XML, or anything custom,
specific to the business. We learned about different categories of APIs and
had a first look at the ASP.NET Web API. After that, we put everything into
context and saw how the web world has evolved and affected the way we
write code.
In the next chapters, we will set up our environments, learn must-
know WEB concepts that we will use throughout the book, and then start
building our API.
18
CHAPTER 2
Introduction to
the Web
In this chapter, we will explore how the internet works and how
information travels over the internet. We will learn what happens every
time we navigate to a website. All the small blocks in this chapter are very
important for any web developer, even if they only write APIs or plan to use
other application models, such as .NET MVC or Razor Pages.
We will learn what a request and a response are, how we can add
meaning to them, and how to leverage the underlying protocol. We will use
these concepts extensively once we start creating our APIs.
Protocols
A protocol is a set of rules that defines how data is exchanged within
or between computers (machines). Or, in other words, a protocol is a
convention between parties regarding the information exchange or
communication between them.
HTTP Protocol
HTTP is the acronym for HyperText Transfer Protocol. It was first coined in
RFC1945 in 1996. It started with version 1.0, and since then it has evolved,
reaching version 3.0.
With HTTP, the information traveling over the network is in clear text,
meaning that with the proper tools a potential attacker might see and use
what data travels between the client and the server and back. You can see a
schematic flow in Figure 2-1.
20
Chapter 2 Introduction to the Web
H
TTPS Protocol
HTTPS (HTTP Secured) is a version of HTTP where the information
traveling between the client and the server is encrypted using a certificate
that lives on the web server. That certificate is generated by a certificate
authority for a specific domain and or its subdomain. It has an expiration
date, which means that from time to time it needs to be renewed.
HTTPS provides a reasonable security level in unsecured networks,
and this means that transmitting sensitive data like passwords or credit
card numbers is safe. In this case, a potential attacker cannot see, in
clear text (Figure 2-2), what the details transmitted are (as was the case
for HTTP).
21
Chapter 2 Introduction to the Web
Client–Server Architecture
The client–server architecture is the simplest type of architecture you
could ever find in the development world. It involves two entities, shown
in Figure 2-3, that are able to communicate and understand what each
other wants by decoding the bits and pieces that reach them.1
Client
In most cases, the client is the one that initiates the communication by
sending a request. We talk more in-depth about requests in a dedicated
section.
1
https://datatracker.ietf.org/doc/html/rfc1945
22
Chapter 2 Introduction to the Web
Server
The server is the entity that receives requests from clients, processes them,
and generates responses back to them. Of course, the response generation
happens if the initial request can be interpreted by the server.
Schema
The schema or protocol shows what is used in terms of transport. Usually,
you will find HTTP, HTTPS, or, in some cases, FTP.
The protocol will always be followed by the protocol separator, ://,
and even if we don’t often type it ourselves, the browsers add it in for us. In
the API world, we will make a clear distinction between HTTP and HTTPS,
23
Random documents with unrelated
content Scribd suggests to you:
Muutamia päiviä sen jälkeen oli Reinillä kokous syytettyjen
yliopistonopettajien kanssa neuvotellaksensa heidän kanssaan siitä,
mitä hän voisi ilmoittaa Plehwelle heidän tulevasta
suhtautumisestaan. Mielipiteet olivat vähän eroavia. Wrede oli
vähimmän taipuvainen myönnytyksiin. Kirje kanslerille lähti
joulukuun 24 päivänä ja Rein lausui siinä m.m. seuraavaa:
"Käynnillämme annetun lupauksen mukaan olen konsistorin
kokouksessa ilmoittanut Herroille professoreille Teidän Ylhäisyytenne
lausunnon ja on minulla sen lisäksi ollut erityinen kokous
professorien Setälän, Söderhjelmin, Gustafssonin, vapaah. Wreden,
Schybergsonin ja O. Donnerin kanssa, jotka Teidän Ylh. nimenomaan
mainitsi sellaisina, jotka ovat tehneet itsensä syypäiksi erikoisesti
virkamiehille sopimattomiin poliittisiin mielipiteenilmauksiin. Nämä
Herrat ovat tällöin selittäneet, että he, mitä tulee tähän Teidän Ylh.
lausuntoon, täysin hyväksyvät sen vastuun, mikä julkisesta
esiintymisestä nykyisissä oloissa seuraa, sekä että he, välttääksensä
saattamasta ikävyyksiä yliopistolle, ovat päättäneet noudattaa
tarpeellista varovaisuutta julkisissa lausunnoissaan. Jos joku kohta
heidän puheissaan tai esitelmissään on voitu käsittää sisältävän
mielenosoituksen hallitusta vastaan tai lainoitusta
vallankumouksellisiin hankkeisiin, ei sellainen mitenkään ole ollut
heidän tarkoituksensa. Täten eivät he kuitenkaan ole tahtoneet
vastaisuuden varalta luopua oikeudesta julkisesti lausua ajatuksensa,
mikä lain mukaan on kaikkien Suomen kansalaisten oikeus, myöskin
virkamiesten virantoimensa ulkopuolella." Kirjeessä seurasi sitten
Schybergsonin ja Setälän antamia erikoisia selityksiä heitä vastaan
tehtyjen syytösten johdosta. Kirje päättyi täten: "Siihen nähden,
mitä minulla ylläolevassa on ollut kunnia esiintuoda, ja koska minä,
kuultuani kyseessäolevien professorien selitykset, olen vakuutettu
siitä, että he vastedes välttävät sellaisia lausuntoja, jotka ovat
herättäneet Teidän Ylh. tyytymättömyyden, rohkenen toivoa, että
Teidän Ylh. hyväntahtoisesti suvaitsee olla H. Majesteetillensa
ehdottamatta mitään ankaria toimenpiteitä yliopiston opettajia
vastaan, jotka tähän saakka kaiken virantoimensa aikana ovat
osoittaneet lojaalista ja joka suhteessa moitteetonta käytöstä ja
hoitaneet innolla ja taitavuudella opettajatointaan."
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