Building Web APIs Part1

Building Web APIs Part1


>>On today’s
Visual Studio Toolbox, Chris Woodruff and I
are going to start our conversation on how
you build Web APIs. Hi, welcome to
Visual Studio Toolbox. I’m your host, Robert Green, and joining me today is
Chris Woodruff. Hey, Chris.>>Hey, Robert, how are you?>>Good. Welcome to the show.>>Thank you.>>Welcome to the cozy confines
of Studio B, it’s great.>>Oh, I like it. It’s intimate.>>Yeah, it’s intimate.>>It’s like there should be a fireplace in here or something.>>That’d be awesome.>>Yeah, cozy fireplace.>>Yeah. Although it’s
90 degrees outside, I’m not sure how much we
need a fireplace right now. But come winter time
that would be handy.>>You may.>>Chris is here to
talk about Web API.>>Yeah.>>Now, this is
an interesting topic. So, Web API is basically
the modern way of having services
running in the Cloud that serve up data
typically, right? We’ve done this before. We’ve had as SMX web
services and WCF, and then there was Web API, which is RESTful and we’ve been doing this for quite some time.>>We have lots away. RPC way back in the day, yeah.>>Yeah, but I think it’s
getting a little bit easier to do and we’re going to look at creating them using ASP Core, which is will wind
up being faster because .NET Core is
really fast these days. We’ll talk about how
you create them, what they look like. So, if you’re somebody like me who is coming
from the WCF frame, I’ve written a lot
of WCF services. I have a bunch of existing
ones that I would love to turn into Web API.>>Yeah.>>How do you build a Web API? What does it look like? What’s the plumbing, the routing, and all the rest of that? We’ll talk about that. Where you would put
all your logic? What that looks like? The benefit, of course, of the Web API is that it gives us our world where you have a service
running in the Cloud, and any client at all, basically passes it
a string with a request.>>Yeah.>>The service reads that string, goes off and does
whatever it does, whether it’s written in whatever it’s written in, who cares?>>Yeah.>>Then packages up your data, sends it back as a string, typically in JSON format, and there’s really cool tools for working back and forth
between JSON and C#. If you’re a .NET developer, if you’re not, then you just
get JSON back. Everybody->>Yeah. Everyone
can do that with JavaScript because
JavaScript uses JSON.>>The problem with
WCF, of course, as it rely on SOAP,
which is powerful, but then your client had
to have knowledge of SOAP. If your client didn’t, then you would have to write
that support yourself. Who wants to do that?
Web API is just completely open and neutral.>>So, we are leveraging
the power of the Internet.>>Yes.>>So, we’re leveraging HTTP. So, everyone uses HTTP?>>Yeah.>>So, we’re actually going
to leverage the HTTP calls.>>Right.>>So, in a sense, you hit the nail on the head. A string comes across
but there’s also another piece of information
that comes across with it, that would be the HTTP verb.>>Right.>>So, we have to know
if just like SQL, some people don’t
like to talk about HTTP and rest with the SQL, the idea, but for some people->>Get it select. There is a pause, right? Add, insert, update,
delete; it’s CRUD, right? Whatever the verb is, so what?>>I know. I do because, for people they’re coming
into the RESTful world, it makes things a little bit
easier to show them, maybe use some of
their knowledge that they have from T-SQL, and then they can understand to be a little more comfortable
in the HTTP world. So, yeah. So, it’s
actually really easy. They have made, I mean, the ASP.NET Core team has
made things extremely simple.>>All right. So, prove that.>>Prove it?>>That’s a great
segue into demos. Prove it. Let’s write
ourselves a Web API.>>So, we’re going to write
an API that connects up to.>>It’s not working? There we go. This is why the clock’s
hidden, by the way.>>There we go. That was strange. Okay. I’ll pause a little bit. So, we’re going to
build an API against a database that Microsoft created a number of years
ago. It’s called Chinook.>>Okay.>>You ever heard Chinook?>>It’s a delicious salmon in addition to being
a simple database.>>It is. I love the salmon. But Chinook is a
database that has, it simulates
an online music store, the front, and back. So, I like it because it
has a whole bunch of like cool rock artists and
Albums and tracks, and it’s much more
interesting than Northwind.>>Yes.>>Anything is more interesting. Sorry, but anything’s more interesting than Northwind
and bicycle parts. So, I’m going to use Chinook. Actually, Chinook went away, I have it on my GitHub because it was going
away and what’s the old->>Going away? I thought
data never dies?>>Well, it doesn’t. But, what’s the old? CodePlex.>>Yeah.>>So, Chinook used
to be in CodePlex,>>Okay.>>And then it went down. You can still get it but
no one’s updating it, because CodePlex
can’t be updated.>>Okay.>>So, I grabbed everything
and you can find it out on my GitHub repository,
in my space.>>We’ll put a link to that
in the show, all right?>>Yes. So, let’s do this. So, it’s really simple. So, like everything, we’re going to start
with a new project. So, we’re going to
go under .NET Core, and then we’re going to
do ASP.NET Core Web App. I’m going to change
over and, well, let’s browse because I always put things in
my Projects folder. So, then, let’s just
call it ChinookCoreAPI. Pretty simple. So,
we’re going say, okay. We get the next stage, and this is going to be an API. We’re going to use
ASP.NET Core 2.1. For this demo, just to
make things easier, I’m going to turn off HTTPS. You can leave it on. I mean, you need to leave it on when you actually build
something for production, but to make this demo, it’s just one less thing
I have to worry about-.>>Okay.>>-and we’re going to show->>If you’re making a public
API that anyone can use, would you need HTTPS?>>Yes. Because, remember, Google, and with Chrome, and I think Microsoft with Edge are setting in up
with those browsers. If you don’t use HTTPS, you’ll start getting warnings, or people accessing
your API, well, mostly websites will start getting warnings from browsers.>>Okay.>>So, it is good to use HTTPS. If nothing else, it’s all
encrypted between your API and who’s ever getting
it on the other side.>>Okay.>>Okay. So, we’re
going to say, okay. It’s going to stand
up everything. Let it kind of figure it out. Let’s pull all of
its dependencies in. So, what I’m going to do to begin with is the project always comes with some
initial controller and some initial logic. I’m just going to delete
that, we don’t need it. Then the other thing is, under your project properties, if you go to “Debug
you will find that there will be an API/values because when you first
launch your browser, it wants to go out to that controller that
initially created. But we don’t want
that controller, we are going to create our own.>>Okay.>>So, I’m just going
to say, “API/.” So, let’s save that. Now we’re at
a good starting point. So I have a number of packages
that I have to install. Again, I copied them
from a text file and we’re just going to
bring that text file in. Let me go grab that. So, we’re installing
all the packages that we need for any
of the framework core, SubSQL Server, SQL Server Design and then
any framework core tools. So, you need that
especially when you have an existing database
that you’re going to be generating your models on.>>Right.>>I like using
existing databases. I’m not really a
code first type of person that does
migrations and stuff. I was a DBA, for a couple of projects, so I like having
real databases that are fully tuned and that run well and have good indexes
and stuff like that. I’m old fashioned. I guess. So, we have everything
that we need. The next thing that we need to do is we need to use
a command called Scaffold-Dbcontext and I’m
going to copy this in, I’m going to paste this in and I’m going to
explain what it is. So, it’s a command
that will generate your DbContext in all
of your entity models. So, you give it that
command and then you give it your connection string. So I’m going a run off of
a local database and I’m going to use trusted connection. But then you have to give it the type of database that
you’re going to be using.>>Right.>>So, that’s where it comes
in and you have to say, ” Microsoft.Entity Framework
Core.SqlServer,” just say I’m going to be
using a SQL Server. If you’re using Azure SQL, you use SQL Server. Then the last thing you
need to do is give it a parameter called OutputDir. OutputDir is where
you want all of your generated code to be put. I just say, “-OutputDir Models.” That will create a model’s class in your project and then it will put all those new
generated files out there. So, we’re going to run that. It takes a second to go through. Don’t worry about that, sometimes you will have that, if I run it again. Sometimes, Entity Framework Core
is a little funny with Scaffold-DbContext I’ve had this.>>I might have missed this part.>>Okay.>>Where did you tell it
what database you were using?>>So, in my connection string, if you take a look here, I have a server just server dot.>>Okay.>>So, that just means
the local SQL Server. Then I have a database just called Chinook then I just say, “Trusted connection equals true.” So it’s really simple,
but you can have.>>It all behind the scenes here I can’t
really read that tag.>>Sorry.>>No worry.>>I can increase or I can
fix the resolution I guess.>>That’s good enough. Go ahead.>>Yeah. So, this will
generate all of your models. So, at this point, we have our ChinookContext, so should be very familiar.>>So far this is pretty standard stuff, Entity Framework.>>So, it’s pretty
much the same thing. If you know Entity Framework 6, you should know
99 percent of grindcore. I will say core is still a subset of in
some ways a subset. It has some things
that six doesn’t have but it has lots of
things that six has and that hasn’t been
brought into the library.>>Then just the sidely
you’ve got the warning with the squiggles because you have your secrets buried in your code. We did an entire
episode on secrets.>>I will do that. I always do that because
I can’t hide my secret.>>We did a whole
episode on that.>>Good. That’s awesome
because that needs to happen.>>Leave it in there for now.>>Actually, right now
I can just delete it.>>Okay.>>We’re not going to
worry about anymore. Because I’ll show you
how we take care of it, which you may have
already shown in a previous episode but
I’ll go through it again for it’s worth
repeating that. So, we have this, we have our generated files. Now, we’re going to go and we’re going to work on our Start Up. Start up that CS is
the new core way of kind of standing up all of
your services and doing your dependency injection
and stuff like that. So, but first, I’m going to
go to my app settings.json. Settings.json is kind of like if you remember
the old web.config. You can keep a bunch
of stuff in there while app settings.json is a json file that you
can put stuff in there that your project
can go out and get. So, I just have
some trusted code, so I can put my
connection string out here. So, in here, I have connection strings and
then in underneath connection strings in
that area I should know Db. Then the same connection
string that we use to generate the files in all the models in
the DbContext, same exact one. Now, you could give
it a different one, you could say, “You know what, I have Chinook running locally but I also have
Chinook running up in the Cloud and I generated
and they’re both the same and I want to point
my actual APIs up in the Cloud. You can do that. So, it’s
just a connection string, but we’re going to keep it local. Now we’re going to go over
to “Start Up” and we’re going to go into
“Configure services”. In here, we’re going to
put in some more code. You can see, I
don’t like to type, I’m a little lazy. So, we’re going to put
in two lines of code. So, in here and you can see
we have some squiggly lines. Let’s fix those squiggly
lines real quick. So, we’re going to
point to models to get our ChinookContext
and then we need to bring in the Microsoft.Entity.FrameworkCore
library, for our using clauses. So, at this point, we have a line that says, “I have a connection string and I’m going to go
through configuration, get connection string and
then it’s called ChinookDb. That’s what we did
in appsettings.json.>>Okay.>>So, we’re just leveraging something that’s
already been given to us and in the
configuration object that has become that
core gives you, and then we’re just going to say, “We’re going to do dependency injection,”
and we’re going to say, “Our services we’re
going to inject our DbContext and we’re going
to say, “AddDbcontext.” It’s a type ChinookContext. Then, in there,
we’re going to say, “Options use SQL Server,” and then we’re going to give
it the connection string.>>Okay.>>So, we are building and
setting up our DbContext, at the very start of our project and injecting it in so
that everyone can use it. No one should be able to get our connection string,
it’s pretty hidden. Also, if you send
this out to Azure, Azure will override it
through the web app, if you use a web app services. You can actually overwrite
that by having a setting, by putting a different
connection string and it will inject it into here without you
having to change any code, which is very nice. So, at this point, we have our DbContext
has been injected into our application to be used. So, let’s go back over
to the DbContext. Before I got rid of
everything and I’m configuring because I
don’t need that anymore. I’ve already set up that connection string
before I injected it. So, that’s why I don’t really need to have
that in there anymore. So, at this point
we’re pretty good. The last thing that we need to do is have our controllers, right?>>Right.>>So, we need to know
how we’re going to route these HTTP calls to the right controllers and actions in those controllers.>>Right.>>Okay. This is
really simple to->>Because you deleted that->>I did.>>-that controller.>>Because it was->>-it wasn’t the one, right. It’s not the one
you wanted, right.>>It’s not the one I want.
So, let’s take a look. So, if I say, “Add Controller”, see down here, we have API
controller with action using->>This is one of my favorite
features of all time. This will build
the controller for you.>>Yes. For
us lazy people, right? It will at least get
you the starting point.>>The least plumbing I
can write the better. I want to focus on
my business logic.>>I do. I want to focus on getting something
up and running and then really customizing
it to what I want. So, model class, we’re just
going to go through a couple->>Well, I continue to
think there should be the ability to create
one for all of them.>>Yeah. So, I worked with JetBrains and we have some tools, like we have ReSharper, and I’m actually
building a plug-in->>Cool.>>-for ReSharper to do that. Then, it’s going to
go for a writer which is our dot, dot ID. But I can’t say that
too much around Microsoft world, around here.>>Will it work
with Visual Studio?>>It will work with ReSharper.>>Okay.>>So, it won’t work with- but if you have
ReSharper installed, it should work with that.>>Okay.>>So, I’m actually
building it right now.>>All right.>>So, what that’s going to
do is it’s going to find just like this does
with the drop down.>>Right.>>It’s going to
find everything all these different model
classes, and then->>Well, I tell you what? If
you write it as an extension of Visual Studio, I’ll have
you on the show to show it.>>Yeah, maybe I can write it->>That’s her in VST.>>-also with an extension.>>You should be able to.>>Oh, you should be able to
it shouldn’t be that hard. So, I’m going to do Album. So, Album is a model
class in our API, and then I’m going to say, my day the context class
is that Chinook context. Then, it will auto-generate
the controller name. You can change it if you want, but what you have to remember is because MVC has some convention, you have to have the model name controller
kind of have to go->>The plumbing is expecting, it’s called the controllers so it’s easier just
to leave it that way; otherwise, you’d have to
go mess with the plumbing.>>Mess with the plumbing
and you have to start really adding a lot of codes
to start up. So->>Now, you’re moving away
from your idea of focusing on->>Yes.>>-the code that
you need to write.>>Yes.>>Yeah.>>You can do it but it takes a lot more work and
hoops to go through. So, it’s setting up a controller. Let me close out the models. I’ll open up the controller
folder so you can see that. In here, it actually
set up a route for us. So, remember, we had API, so it’s API/controller name, whatever the controller name
which in this instance, it’s going to be Albums, and it set up everything
that it needed. It actually has already set up the Internal Private read-only property for Chinook contacts, which on the constructor uses dependency injection to get that context and so
everything can use it.>>Okay.>>So, we don’t even have
to write any code to connect or initially connect our instructors or connect our controllers to
our DB context.>>Yeah.>>Now, for demo purposes,
this is great.>>Right.>>I love this. For production, I don’t do it this way. We’ll look at another episode where we’ll look at some
more advanced architectures.>>Okay.>>But for this simple
demo, this is fine. So, we have a command
called Get Album, and you can see that there are all marked up with
some annotations. So, we have HTTPGet. So, the one thing
that differentiates a controller from
traditional MVC and one that we use in Web APIs
is that we decorate our actions with
these HTTP verb attributes. So, you can see that
we have HTTPGet. Down here, when we want
to get a single Album, we have HTTPGet, and then it has an ID that
comes along with it. We have HTTPut. So, this will do an update. So, if we want to
update an Album, we will set up
that annotation of HTTPPut, and then we have a post, so this will add a new Album to whatever data repository that we’re using on the back end, SQL server in our case. The last one is HTTPDelete. So, we’re going to
use those four, we’re going to leverage those for HTTP verbs for this demo.>>So, the scaffolding
built your basic CRUD?>>It built pretty much
everything that you need to do.>>Then if you have
more advanced data logic, you can just swap out the actual code in here
with whatever you want-.>>Yeah.>>-as long as you
have any Frameworks 6, it’s not .NetCore. So, as long as you’re
writing code that supported by .NetCore to that one
and any Framework 6, you can do whatever
you want in here, whether it’s validation or you’re going to different places, or you’re massaging the data,
whatever you need to do; you can put that code in here.>>It does do some validation. So, let’s take
a look at the post. We do come in here
and it does check to see if it’s valid; if the macrostate is valid.>>Okay.>>If it’s not, it will
return a bad request. So, a bad request is a 404. So, you can, there are
calls to send back, you can send back
whatever response code, HTTP response code that you want, but ASP.NET Core has a lot of these simple things
that we can do. So, if I want a bad request,
I can do that. If I want an okay, I can do that. If I want some kind of 500 error, there’s a very verbose
call to do that. Or I can have just respond with specific response code and then put my own message into it, so it’s quite flexible. But for this, we’re going
to leave it for that. Now, one thing I do want to say, you brought up
the business logic. So, I don’t know
if you’re like me, but I don’t like to delete
data in my databases. I like to deprecate it. So, I like to just have
a bit that says like, visible or not visible. So, you could come in here
into this Delete Album action, and instead of doing
a remove down here, you could do an update.>>Right.>>You could just
update that record.>>Yeah. Or archive it
or whatever you want.>>Yeah.>>The point is
here that you can->>You have control.>>Right. That it wrote some nice templated
boilerplate code for you which may
be all you need, or you can call out to other
services, whatever you want.>>Yeah. So, let’s add
one more controller because I like to have
at least two controllers. So, let’s go down here
and we’ll do Artist. So, it’s already set up. It remembers the last DB
contacts that you use, so you don’t have to select
that and we get another one. Now, I’m going to clear this out so we don’t see that red. I’m going to build this
to make sure it builds.>>Okay. Then, let’s
see if it will run.>>Of course, it’ll run.
Why wouldn’t it run?>>It should.>>It should. It’s
my least favorite word in all of technology. It should.>>Okay.>>It should work.>>So, we’ve got
a page can’t be found, which is good because we actually haven’t given it a valid right. So, all we have up here is localhost and then the port
that we’re using, and then Flash API. So, if I said Albums because remember we
said up an Album’s controller, and in there we had a route
that said that anything from API Flash controller name would come into that controller, into the corresponding action.>>Yay, tada, look at that.>>I use a add-in for Chrome that makes my JSON look fine. So, if it looks like this, if you get a row, don’t worry, it’s fine. I just have it
parsed so I can see.>>Okay.>>We have it. So,
if I want to do, let’s say, 42 is
my favorite number. So, if I want to say, “give me the Album that
the Album ID is 42. I just say, Albums slash 42, and that route would go
to the Get with an ID.>>Yeah.>>I get back Album 42. So, it’s that simple to set
up your Web API project.>>Right.>>That’s all you need to do.>>Cool.>>It’s really simple.>>Then, all you need
to do to call it is pass the correct string.>>Yeah.>>However, your deck gets done.>>Yeah, and you can
use a Web browser, but you can’t do anything other than a Get
with a Web browser. So, if you want to test out and you want
to try out your APIs, there’s a few different
applications that you can use. I use Fiddler or I use Postman.>>Okay.>>They’re both free. They’re both free applications that you can install locally. Postman will run locally
or through Chrome, or through, I don’t know
if there’s an Edge.>>I don’t know.>>I don’t know. But,
I just run it locally, and I can call, and I can say, “Here’s my string that
I’m going to send over, and my verb,” and I can
even set up headers in my HTTP call to set things like authentication
and stuff like that. So, we’re not even going
to look at all of that, but there’s a whole
rich experience around authenticating
around your Web APIs, and you can do that yourself. Where there’s
third party companies in the partners ecosystem that will allow you to wrap and help you out with
your authentication.>>Now, that you have
this API written, tested, proven, you can run
it in IaaS locally. You can publish it up to Azure. You can run it in a container. There’s all kinds of
things you can do.>>Yeah. Because
it’s ASP.NET CORE, I can run it on Mac OS or Linux. Like you said, I can
run it on any number of different instances of Azure. So, I can run it on a Web App
that is of type Windows, or of type Linux. I can put it up in
a container and because Linux containers
are so cheap on Azure, it’s perfectly fine to
throw it up on that. Kubernetes, you can use
that with Kubernetes. So, yeah. You can put
it just about anywhere.>>All right.>>So, yeah. So, there you go.
It’s that simple.>>It is simple.>>It is.>>You said earlier,
it’s easy to do, I said prove it, you proved it.>>Yeah.>>Awesome.>>So, I do warn people. I ask anyone, if you’re
going to be using Web API, learn a little bit about HTTP.>>Sure. Absolutely.>>Yeah.>>Right. Same thing
if you get a, oh, with XML and if you
know C# with XML, you can build mobile Apps. Of course, you can,
but you need to learn about iOS and Android.>>Yeah.>>You need to learn about
the operating system.>>Yeah.>>If you’re going
to build Web API, you need to learn some Web stuff.>>Yeah.>>But, this seems
like if you are coming from more of
a client side world and you want to start
learning Web stuff, this seems like
a great place to start.>>It is. I mean, it’s simpler. I think it’s simpler than MVC. Because you don’t have
to worry about views and you don’t have to
worry about all that. You’re just basically
getting those HTTP calls.>>Right.>>Sending up your controller, and then you can build
whatever logic you want to use. More advanced stuff, you can
use a repository pattern to pull out your business logic from your controller actions, which I don’t suggest
that you put your code, your business logic directly
into those actions. I build them into repositories that I put in the other projects, so I can share them
and I can test them. So, the biggest reason
why I don’t put everything into my controllers
is because of testability.>>Right. Okay.>>Because I want my API calls and my business logic
to be independent, so I can test and make sure that they’re working
independently.>>Cool. So, this is going to
wind up being three parts.>>Hopefully some parts.>>Maybe more.>>We are.>>I will do three now.>>Yeah.>>We hopefully do
follow-up ones later.>>Yeah.>>So, we just
covered the overview. We’re going to do
some integration testing next, and then you’re going
to show us some best practices in part three.>>Yes.>>Cool. So, hope you
enjoyed this one and we’ll see you next time
on Visual Studio Toolbox.

23 thoughts on “Building Web APIs Part1”

  1. I'm just amazed at how Microsoft seems absolutely oblivious of the growing functional programming trend, especially for new projects. And the irony is Microsoft currently has the smartest functional language on the planet, F#, with a substantial head start on everything else. Again and again these videos don't even mention F# much less make a token effort at using this "first class language." At the moment, F# is literally the only FP that can build native apps, APIs, web apps, etc. By the time Microsoft wakes up to its functional programming advantage, it will have squandered its lead and something like Facebook's ReasonML will be the industry standard.

  2. Chris Woodruff you are wrong about putting business logic in your Repository. Business logic belongs in your services. Repositories are obsolete if your using NoSQL, but if you must make a Repository, it's isolated responsibility is to get and persist data, not enforce business rules.

  3. Chris, Robert, use your Chinook Database and AutoAPI from https://github.com/proinfocus/AutoAPI. It will take just a setting up of project and connection string to accomplish the exact same thing you have done in this video. Please try out and let me know your opinion and suggestions.

  4. Alaydyn Gholechragh

    vs code problem

    https://social.technet.microsoft.com/Forums/en-US/8ad0fbb0-bcb6-4811-addf-c507b599e79e/i-cant-solve-this-error-vs-code-not-open-no-network?forum=MTCWin8

  5. Maybe you could put the text from the notepad to install the packages and create the model in the video description section above

  6. That line getting the connection string out of the config file does not work. Hard-coding the connection string in the UseSqlServer("myconnectionstring") works

Leave a Reply

Your email address will not be published. Required fields are marked *