510

September 14th, 2022 × #API#Development#Programming

How To Build an API in 2022

This podcast episode provides a comprehensive overview of building a web API, covering topics like the various layers and components involved, popular API types like REST and GraphQL, authentication and permissions, caching, database options, and more.

or
Topic 0 00:00

Transcript

Announcer

You're listening to Syntax, the podcast with the tastiest web development treats out there. Strap yourself in and get ready. Here is Scott Talinski and Wes Bos.

Topic 1 00:11

How to build an API

Wes Bos

Welcome to Syntax, a podcast with the tastiest web development treats out there. Today, we've Got a show for you today. How to build an API. This is something we did, I don't know, probably 3 or 4 years ago. Rid. So we are going to do an updated version of that. How do you build an API? What is it? What are the parts that go into it? Should you put all of the pieces together ready. Should you reach for an off the shelf solution that sort of does a lot of that for you? We are sponsored by 3 awesome companies today. The first one is PaymentsHub rid. Debportal, your integrated payments partner to onboard and underrate your merchants.

Wes Bos

LogRocket.

Wes Bos

They do JavaScript rid session, replay, and FreshBooks cloud accounting. We'll talk about all of them partway through the episode.

Wes Bos

My name is Wes Boss. Rid. I'm a developer from Canada. And with with me, as always, is mister Scott Talinski. How are you doing today, Scott? Hey. I'm doing good. Doing good. Yeah. Just,

Guest 2

You know me doing my stuff, working on my my Svelte refactor, my my website. It feels like you're in that zone of of redesign where It's it feels like 80% there, but the reality is it's probably closer to 50%. Yeah. Just it looks like it's 80% there. So there's so many times I'm looking at them, like, this thing's basically done. And then I just went through last night, and I I kinda did one of those rid. Write down every single thing that needs to be done with it. And I'm just staring at a massive a massive Color corded color coordinated color coded? Color cord color corded? Color coded. Color coordinated.

Guest 2

Color coordinated. All of those things, to do list of, like, what I need to get done for what time and then what feature, What section of the website? And I'm just like, I gotta get some work done.

Wes Bos

Oh, yeah. That's that's the most frustrating thing. And that's Why people don't finish things is that, like, the last 10% really isn't 10%. It feels like you're almost there, but in reality, it takes Almost twice as just as long as you spent so far to get it polished into a point where it's totally finished up. Oh, totally. Maybe a show that we should have at some point is, like, rid Estimating and understanding that the tiny little polish, the little click handler that has an edge case rid. Takes 5 hours, whereas the initial implementation took you 1 hour to implement. Pushing through that last bit. Yeah. Yeah, exactly. Rid Alright. So, let's let's get on into it. An API. Let's talk about what is an API and what why you might need an API. So The web is generally built on on APIs, and what that means is that you have servers that will take in requests rid based on what you want to do. So literally every single thing that you do, you type into a box and you click on save. You click on an x to delete something. You ready. Edit something and update it and click the save button every single time that you perform an action, send a tweet like a like a video.

Topic 2 02:33

What is an API and why you need one

Wes Bos

They take what you've done in the UI and send that information to a server.

Wes Bos

And that server generally has a bunch of API, what they're called endpoints, that can interpret those instructions and do what it is that you want. So post the comment on the video, like the items, start recording, send a notification to someone. There's all kinds of stuff that Sort of needs to happen.

Wes Bos

And generally, if you're building a back end, a large portion of what you are building on the back end is The instructions of what needs to happen when somebody does a specific thing, and that is what an API is is that a good idea of what an API is got? Yeah. I would say so. I

Guest 2

I have some, like, thoughts going around in my head about An episode I wanted to do, about, like, do you need an API? Because I I've kind of As as we're getting closer and closer to our PHP versions of our websites, I kind of get less into the territory of, needing an API or feeling like most sites need an API. So if you're wondering and you're sitting there, like, do I really need This do I really need an API? It really depends on what you're building. Right? It depends on who's consuming it, how many places are consuming it, and and what exists there. But,

Wes Bos

rid. I I think your explanation of what an API is is fantastic. Yes. Yeah. And I I guess there's probably different levels of API because, like, if you have Let's say you have a PHP website and you make a file called add. PHP.

Wes Bos

And so when somebody hits that website with a post request and it adds something to the database that that is an API, right? Like, you know, it doesn't have to be, like, a full blown

Guest 2

standard

Wes Bos

with the documentation and types and everything. It simply just could be A URL that somebody visits, or you fetch request to and hit it. There's certainly different levels of it. And rid. I would recommend, if you have never built an API, definitely throw most of this out the window and just start with a simple rid. Route in your application that when posted to or hit, with a fetch request will Do something.

Guest 2

Yeah. I guess what I was getting at was more of, like, you know, WordPress sites typically before If if you're not thinking about, like, WP, JSON, whatever. Yeah. You hit the server, it returns HTML

Wes Bos

data. Right? Yeah. Yeah. You're right. Like a Like a website or like server rendered application. I guess that's true. Like most like most websites, if it's not an application that does things, but it simply just Serves up HTML, then, yeah, definitely doesn't need an API.

Guest 2

Yeah. Totally. Okay. Cool. Well, let's rid into, like, different types of APIs that you might see around their words or or I guess most of these are acronyms. Although I found out GraphQL is not really an acronym or anything. It's just a its own word.

Guest 2

So we have REST.

Topic 3 06:22

Types of APIs - REST, GraphQL, gRPC, TRPC

Guest 2

We have GraphQL.

Guest 2

We have gRPC, and we have rid. T r PC. These aren't, like, the only options here, but these are the kind of the big boys. With rest, what you're doing is you're sending over A git post put delete, via HTTP requests.

Guest 2

You're sending those messages to the server. The server accepts whatever rid type of message that is to the given location.

Guest 2

And then it handles that information on the server side and will either return data correctly or return just a general response saying that that data was received or or the process that had been modification, rid. Whatever had been received successfully.

Wes Bos

Yeah. I would say it's it's really hard to say, but, like, most of the web Is built upon REST, I would I would say, because REST has been around for the longest. And and REST is not All of these things that we're talking about, REST, GraphQL, gRPC and tRPC.

Wes Bos

These are not something that you install. These are just ideas In general, that, when you tRPC you installed. Okay. Sorry. TRPC is one, but the rest of them are not things that you install. You certainly can install GraphQL, but the whole idea of GraphQL was initially just created in text form And say and then there are implementations of it in every single language. So at a very simple in PHP, again, like you make add. PHP, And when somebody visits that URL, that's a GET request or if somebody pings it with a fetch request, that's generally a POST or a PUT rid. Request.

Wes Bos

And I would say that those are the most popular out there because it's been around for the longest time. In the last, what, rid. 4 or 5 years, GraphQL has become much more popular because the Problems with REST APIs is that generally you want to fetch multiple things at once. Like, let's say we wanted to list Fetch a list of podcasts, but also a list of podcast hosts.

Wes Bos

Well, we could hit the API for podcasts. And there might be some parameters like limit. I want the 10.

Wes Bos

But then what if you don't want the show notes for every single one? Well, that's a lot of data coming across the wire if you don't necessarily need the show notes for each one. So then you create a second API endpoint rid Or you you come up with, there's a there's a lot of implementations around it. Elasticsearch has their own where you can say which fields you want. But That's essentially what GraphQL is, is that you can request multiple pieces of information and just the fields that you want in a single go.

Wes Bos

Rid. And, there's a bunch of more benefits to it. It has its own query interface. You can do mutations as well with it.

Wes Bos

And it is a bit nicer to work with. REST API is just super simple. You can return literally any data you want. GraphQL is a little bit more involved. You have to type most of your inputs and outputs, and you have to have a little bit more structure around how it works.

Wes Bos

But if you are building a larger API and something that needs to be a little bit more maintainable, at least right now, I say it's probably a little bit more preferable.

Guest 2

Yeah. It's interesting. I I've had a it's so funny. I have so much conflict in my my brain these days about APIs, and, I I have some interesting feelings about GraphQL lately where I just wonder if it there's for the majority of people using it, if they really need it, rid. In terms of, like, what it's doing for you, because there are a ton of benefits to it. Right? The type safety is really great. Type safety up and down your API is really great. Rid. The structure, the organization of everything is really great. In fact, overall, I like working in GraphQL.

Guest 2

You get caching on the client side with many of the clients, and, you can kinda really standardize your APIs across whatever UI you're using. If it's a iOS or a web or whatever, You can utilize the same GraphQL API with really the same queries, same query language even, and and know that exactly everything is going to be the same. And that That's all wonderful. But at the same time, there's potential performance issues that you have to work around.

Guest 2

You have to make sure you're knowledgeable about, like, performance In in plus one issues in GraphQL, you have to manage a whole, infrastructure for your GraphQL.

Guest 2

You end up typing The same schema several times in different ways. There there's definitely, like, I think, trade offs to GraphQL where I really like working in it, But it does feel to me more and more like a GraphQL API is something that makes more sense at a larger, more complex rid. Scale than a smaller scale. Yeah. I'll tell you my,

Wes Bos

my main product, which is selling rid Courses and distributing them, let people watch them, tracking how far they have watched. All of that is done via REST APIs,

Guest 2

rid. Because And mine's done by GraphQL.

Wes Bos

So so there you go. And I certainly have a couple of projects with GraphQL, but, There definitely is something to be said for the simplicity of a REST API, especially when You look at things like RatQuery or a lot of these client side libraries that make ingesting that rid REST API is very, very simple as well. I think that was part of the draw initially to GraphQL is that, oh, the The client side of this, the the the end thing in the browser is really, really nice as well, so I kinda want that. Yeah. I

Guest 2

rid. I ever since I've I've been it's I have a lot of thoughts that I need to I I said I need to marinate on these thoughts a little bit more so I can properly articulate them. Rid them off right now. Yeah. I know. I I was working on, like, a little bit not like a blog post, but, like, an outline even for myself to collect some of these thoughts about, Do I really like, I I I kind of turned into my favorite scene in Bad Santa where Bad Santa is looking at the people stealing things, and he's like, Do you really need all this stuff? Like, do we really need all of it? And I I'm look looking at my API and, like, the 1 file that talks to the other file that talks to the other file to send the thing. And rid. And it almost feels like old school Redux to me where I'm like, do I really need this? Like, is this really Yeah. It's a little bit rid Too much setup and and overhead. And this then I'm glad that you say this because this time tends to happen with literally everything.

Wes Bos

We get this new thing. Everybody says it's the best thing ever, and everyone says he uses to a point where people will ask me, like, rest is dead. They'll tell me rest is dead.

Wes Bos

And then we'll swing the other way.

Wes Bos

Rid. And, like, a couple years later, and people say, okay. Now we're starting to hit some of the growing pains, and maybe it wasn't the the best approach.

Guest 2

I I had I I joke. This is old school heads will get this.

Guest 2

But I had jokily this is entirely a joke, so don't Don't screen cap this audio here, but I I made the joke title for my, like, marination thoughts and blog post was GraphQL is considered harmful. Rid. But just because anytime back in the day, anytime that that cycle would happen, someone would release an inevitable blog post that was this thing is considered harmful, and it was always Hyperbolic or whatever. Yeah. So that would it was just an inside joke on my my end here.

Guest 2

What what about what about gRPC? And, I'll talk about tRPC in a second. But what about gRPC, Wes? Yeah.

Wes Bos

I don't know a whole lot about it. I just know that it is a thing.

Wes Bos

A thing. It's a way to cross platform send messages, and it is very lightweight. So rid. I guess the one thing we didn't mention is one of the benefits of building an API is that the web is not the only place where rid. We interact with with the computers.

Wes Bos

As much as we like to think it, there are other things. There are iOS apps. There's Android apps. There are Cars. There are terminals. There are beacons. There are lots of systems in the world that are not a web browser, And those systems need to talk to the servers as well to get information and save information and update information.

Wes Bos

And generally, those need to communicate via an API as well. So one of the benefits to having an API is that you can use the same server rid. To talk from your drone as your your actual website does as well because they are all based on standards.

Wes Bos

So gRPC is a, a popular what's it called? Something remote procedure call framework. It's created by Google.

Wes Bos

RPC was was the initial one. Who did we rid. I don't recall. It's a lightweight way to to communicate.

Wes Bos

If you use gRPC for something, tweet us at Syntax FM because it's definitely a bit of a blind spot for me, but it seems to be very popular in the outside of web development world.

Guest 2

Yeah. I would say it's a major blind spot for me as well.

Guest 2

I mean, we all have many blind spots.

Guest 2

Next one is tRPC, which is kind of a newer thing here. And tRPC is basically a way of it it's funny. It kinda Feels a little bit like GraphQL meets REST in a way, but it's really it's it's its own thing. Basically, you get end to end type saved APIs with less goff than TypeScript or with with less goff than than GraphQL because you're not necessarily relying on a schema, but you do accept queries kind of the same way where you have rid. Resolver, you accept the query by name, and then you can resolve that that information.

Guest 2

And then you also likewise have a tRPC client Like you do a GraphQL client, and you handle your your client fetching by passing in a single URL like you do in GraphQL.

Guest 2

And the new client dot query, and then you ask for what you want, and it's fully type saved. So what it feels like to me is it Feels like many of the benefits of GraphQL without, some of the pain of GraphQL, some of the setup stuff, some of the that sort of things. I haven't used it. I've only looked at the demos. So if I'm out here miss miss misinterpreting some of these demos in this code, please, let's Let's get this corrected here. We should have Alex on, who's the creator of tRPC.

Guest 2

I know he's expressed,

Wes Bos

interest in chatting. So we should have Alex on on syntax. Rid Maybe we should send him a little message here. It seems to me that the benefit of I'm just looking at some example code right here. It seems that the types are created at the resolver time. Like, you could like, you you're making a type for TypeScript anyway. Like, why not use that for Your API as well, especially with a lot of the early, like, Apollo stuff was like you would have to create these server side types, And then you would have, like, another layer, which was the publicly facing types, because that might not be the same as your database types. And then you also had to create types rid For your client side, if you wanted to have a lot of the fancy caching and and whatnot, and it's just like, this I think this is what you're referring to. It's just like, You know, like, this is a lot of writing, where I just wanna be I just wanna save the freaking thing if I wanted. Rid. It's definitely got a lot better than that, in in the past, but, certainly, I can see the benefit of this thing. They're using rid. A library called Zod.

Wes Bos

What is Zod?

Guest 2

I don't know. Zod sounds like TypeScript.

Wes Bos

First schema validation.

Guest 2

TypeScript

Wes Bos

first schema validation. Looks like they're using it to create the schemas rid In tRPC.

Wes Bos

Yeah. Interesting.

Wes Bos

Interesting. There's a whole world here. I think we need to explore this a little bit further in coming episodes.

Guest 2

Yeah, I'm into that. I've been doing quite a bit of type scripting myself. So this is neat. Oh, TypeScript first scheme of validation with static type inference.

Guest 2

Rid. Interesting.

Wes Bos

Cool. What else is interesting?

Guest 2

Oh, yeah. You know what? You know what I find particularly interesting is getting paid. And rid. If you're that type of a developer who's building things, where you need to collect payment, well, maybe you should be checking out PaymentsHub.

Wes Bos

Yes. PaymentsHub dev portal is our sponsor today, and it's really cool because they have easy to use APIs and SDKs rid. That allow developers to create ecommerce websites, develop endpoint point in person point of sale application, and launch fully featured rid. Omnichannel payment solutions. What does that mean? Well, if you're making an app or a software as a service, and your users need to accept, rid. Accept credit cards from somebody, then, like, you need, like, another step further. Right? Like, those rid. Merchants need to be onboarded and cleared by the credit card process. I don't know if you've ever tried to become a merchant on anywhere. There's a bit of a onboarding or they need to, like, see your business documents and all of that. And it's really tricky. And if you need to do that on behalf of your merchants, You need powerful APIs to be able to do that, and that's what dev portal by PaymentsHub does. You're going to want to check it out at developer. Paymentshub.com Slash syntax.

Wes Bos

You can get your merchants onboarded in as little as 90 minutes. Rid. Syntax listeners who become new partners get 6 months of free data through our business reporting API. Check it out. Thank you, dev portal Payments hub for sponsoring.

Guest 2

Cool. Alright. Let's get into the next section here, which is we're gonna be talking about cake.

Guest 2

We're gonna be talking about cake layers. PHP.

Topic 4 20:46

Database layer of API

Guest 2

Cake dot PHP. Yeah. With so with any type of cake, you have Good cakes, I'm gonna say. Right? If it's a k it's a good cake, you got more than 1 layer. You got layers and layers and layers of cakes here. So we're gonna be talking about essentially The API cake layers and what are types of layers that we have within our API. And usually, the lowest layer, The layer at the bottom is going to be the database layer where your database lives and the or your data lives, I should say. And a database can be any number of any number of technologies. It's so funny. Databases, I think, are pretty divisive, in the tech world where if you say you use 1 type of database, people are always gonna be arguing about it or telling you you gotta use Postgres.

Guest 2

But there's a lot of different database choices out here. Postgres. It's always Postgres. Isn't that right? Like, why are we doing this? Why are we using Postgres? Alright. Well okay.

Guest 2

Well, there's a lot of different choices. You can use any number of databases. There's just an endless amount of them, but the most popular options are Typically, MySQL, Postgres, MongoDB, in terms of, like, the the actual back end database that you're writing. And this is, again, this is where your database lives. And, typically, many people, when they host their database, are hosting a database that lives somewhere else Or it's running on a server somewhere, or maybe it's running on a port of the server that you're you're running on. If you've ever installed a WordPress site. You'll know that you have to configure a MySQL database at some point in that WordPress install.

Guest 2

Likewise, that is your database rid layer in your API or your website. Yeah.

Wes Bos

So when you after you've chosen your database that you want, You generally also choose a way to interact with that database. So you generally need a piece of software that will allow you to rid. Create models, and models are generally the like, I don't know. You have, like, an author model, And your your author, Ronald, okay, that author has an email address. They have a name.

Wes Bos

Maybe they have books that are related. So book could be another model.

Wes Bos

Rid. And most likely, your software allows you to model those out or schema them out.

Wes Bos

And then you generally also have a JavaScript or PHP or whatever way to interact with it. So I use MongoDB, and I use a piece of software called Mongoose, which will allow you to query, create, update, All of that kind of stuff.

Wes Bos

Sometimes they are database specific, like Mongoose is just for MongoDB.

Wes Bos

Sometimes they are not database specific, so they're called ORMs, which allow you to rid. Use the same code, but then you can choose under the hood. They'll translate the things like create, find, delete, update.

Wes Bos

They'll rid. Change those methods to whatever the equivalent is in those databases.

Wes Bos

So, what is the Node. Js ORM that's really popular?

Guest 2

Prism. Prisma?

Wes Bos

Yeah. Prisma is a popular one, but there is even a There's another one that SQLize. That's the one. Okay. That's like a we'll talk about Prisma in just a sec. But Sequelize will allow you to, write Node. Js code, and you can interface with Postgres, MySQL, MariaDB, rid. QLite and SQL Server so you can choose whatever database you want or most likely it's all right. We already have a database That has data in it and I need to be able to interact with it. I'm going to go ahead and use, sequelized rid To to to work directly with that. Yeah. And this I mean, this can

Guest 2

make make the ease of writing SQL queries way better there because you're not actually really writing SQL queries. You're writing SQLized code. You know, it user dot create rather than Exactly. The the the SQL query. And it looks I mean, SQL has given the name should be kind of obvious. It does not support MongoDB style Database schemas or database document style databases, which is, you know, a whole topic That maybe we should get into. I know that's like a kind of a divisive one. People really hate MongoDB even though it's it's very widely used.

Guest 2

Rid. But, yeah, the these database layers and ORMs, I I don't use an ORM myself anymore. I was using Mongoose, but we since moved to native Database validation from MongoDB is would you describe the ORM layer as, like, a a separate layer from

Wes Bos

rid. Just in general, the server layer that you have described here, or would you say it's part of the same thing? I would say it's it's part of the same thing. Like, rid. Yeah. Most people don't really care about the difference between the 2. They just want a npm install something and then be able to rid. Query the data, update the data as they need to, and sometimes that's part of your framework like Laravel.

Wes Bos

Sometimes that's an additional package that you install yourself, like SQLizer, Mongoose, and whatnot. Or sometimes the database will offer bindings themselves. And generally, the bindings ready. Okay. Here's a JavaScript function. You can run that JavaScript function, and it will save an item for you. Generally, The ones that sit on top of the native bindings have a couple of nice features, and it's a little bit easier to use.

Wes Bos

Rid. And then that's always a trade off because you're not

Guest 2

raw to the metal if if that's necessarily what you need. Yeah. Totally. So At a big picture, we need some place for our data to live, and the next layer up is we need some place to be able

Wes Bos

to get or modify our our data. Rid. Let's go to the next section, which is the server layer.

Wes Bos

So this is where the logic for How your data is interacted within. And we should also say, like, you don't necessarily need a database for an API. You could you Could make an API that literally capitalizes a word for you. So maybe this is this is my input transforms output. Exactly.

Topic 5 26:56

Server layer of API

Wes Bos

And if you're thinking, I've never built an API, literally go and make an API right now that has rid. Five endpoints. One that capitalizes, one that uppercases, one that reverses all the words, and then one that adds Two numbers together. And those are silly use cases for an API, but, we've seen sillier out there. And it basically say, okay. Well, now, Anytime I need to add two numbers together, I have a server running somewhere at $5 a month where I can do that.

Guest 2

But what's cool about that example overall is not the usefulness of the API, right, as you know. Yeah. What's cool about that is is it covers so many of the basis. You'll be able to accept a request, parse that request, modify that thing, and then return rid. Information from that request and access it. And that's really, like, what you need to know because once you know how to do that, all, you know, Connecting to a database and modifying or whatever the data from the database, pulling information from them. Those are all different, you know, smaller details here, but

Wes Bos

The big picture is being able to accept that request and do something with it. Exactly. And that and that's what the server does. The server handles the logic. So You have your request. Somebody hits your API, and, generally, that request will have information about what happened. 1st, the method that happened, rid. Get post, put, delete. Those are the big ones. There's a couple other ones.

Wes Bos

Then you generally you have a on a REST API, you have a route, Meaning that somebody hit the route of forward slash API forward slash customer. And if it was a post request, The customer API is, generally, you're creating a customer.

Wes Bos

If you are is it a get request? If you're generally querying a customer. If it's a put request, You're generally updating a customer and delete your generally that's the whole idea. CRUD.

Wes Bos

Create, read, update, delete. That covers 98% of your use cases in in all APIs.

Guest 2

And you do you know what really confused me as a sorry. To well, before you get on to the next bit. As a newer developer, one thing that always really confused me, I remember back in the day taking a code school classes, is the difference between CRUD and rest because create That's true. Update, delete, whatever. What was the art? Remove, create, remove, update, delete, and then get post, put, delete. It's like, How are these things related and, you know, what are the differences there? So just to be clear that get post put those are, You know, essentially, HTTP to send those requests back and forth where CRUD is more or less like a concept of like the stuff you typically need to do with your data. Yeah, exactly.

Wes Bos

So in your server, when somebody hits either an endpoint or if it's GraphQL.

Wes Bos

The GraphQL only has 1 endpoint, but What comes along with the the GraphQL endpoint is either a query or a mutation. A query is you're you're querying data. A mutation usually means you're updating or deleting or mutating data in in some case.

Wes Bos

And the logic For what should happen when these things run are generally either called resolvers or controllers. Those are sort of the 2 big ones that happen. And What will happen is you write code inside of those. You say, Okay, somebody has said, give me a user where the ID is 123.

Wes Bos

So what you'll have to do is you'll write the code.

Wes Bos

The idea is ideas 1, 2, 3, and then you you create the database that comes back. You say, if the user is there, then you return the user. Rid. And then if there is no user return, then you have to return an error message, and and you you generally also, you change the, HTTP response code to something that like not found, response code and whatnot, and all of the logic As to what goes on in there, you might want to do other things like create a customer. You might want to generate a temporary password. Where you might want to email them. You might want to flag their account as created but not approved. There's all kinds of stuff that needs to happen inside of there

Guest 2

other than just a simple crud out there. And you might the important thing to know is that these things at the end of the day, this is all JavaScript where A message comes in to your your route, and you can do anything. It can be a cascade of thing that does thing that does thing that does thing. And as long as, you know, you're making sure that the user is aware of the fact that the server is thinking or processing or doing all these different things, I I mean, you can do a whole lot of stuff. It's not always having to be simple create, update, delete, whatever. It can be a whole cascade of of operations.

Wes Bos

Rid. And we should also say we'll talk about some of these boxed solutions.

Wes Bos

And often you will use a CMS Or something that sort of comes with these things built in, because it also is kind of exhausting to when you are.

Wes Bos

Rid. We talk about, well, not everything is just CRUD, but a lot of it is. A lot of it is simply, I just want an endpoint to query user. I want to be able to update that user. I want to be able to delete that user and writing 4 or 5 rid of different endpoints for every single model that you have is sometimes unnecessary. So a lot of these frameworks will give you the very basics, And then you can step in and say, you know what? That was good, but I need to be able to add in a little bit more. And you can overwrite those. Keystone does this where you're like, okay, I need to write custom logic for the create because when we create the user, I need to be able to rid. Email them and create a slug for them as well. So, that is a use case for the off the shelf ones as well.

Guest 2

Yeah. The off the shelf ones, what you I mean, what you you lose in flexibility and pure whatever, You know, pure control, you gain an ease of use. Yeah. You gain an time spent.

Guest 2

You you gain an time with your children on the weekends.

Guest 2

All sorts all sorts of stuff. Yeah.

Guest 2

Yeah. And you also might gain a whole lot of, You know, nice restful nights where you're not having to worry about if your LogRocket error program is firing off a ton of errors because you've made a mistake on your API and rid UI is having some issues. Well, this is actually a neat feature of LogRocket, which is one of our sponsors, is that when something goes wrong on your website, it gives rid you a session video replay that allows you to see what happened. But we're talking APIs today, and a relevant feature of LogRocket is simply the fact that LogRocket can, give you the network requests in addition to that video. So let's say the user Clicked on a thing. That thing hit your API, and there was an error somewhere in your API. It either returned the wrong information or the request is denied or It hit an endpoint that's returning a 500 error or something. You're gonna be able to get access to that in LogRocket by seeing the actual network request that took place And see it as it happened when the user did the thing so that you can solve this bug and debug your API because You chose to do something super fancy that, you know, you accidentally goofed up because we all make mistakes. Right? Yeah. So head on over to logrocket.comforward/ syntax. Sign up today, and you will get 14 days for free. You can check it out and really get a handle on how your users are using your stuff. Rid. Alright. Let's move on to the next section of the cake, which is the authentication layer.

Topic 6 34:53

Authentication layer of API

Wes Bos

Your API doesn't need rid Authentication at all. We can simply just have it wide open to the world. And in a lot of cases, especially the read APIs or the query APIs, they are wide open to the world, meaning that you don't need any authentication to be able to do it. But generally, there are things like deleting users or querying specific Parts of a user, like, somebody's you wouldn't want someone to be able to query a list of all of your users and their email addresses rid just from being wide open. So generally, you need authentication layer. And I guess maybe we should roll this in permission layer as well, or should that be its own layer of the cake?

Guest 2

They feel very close to me. Yeah. I usually put them together in my mental picture. But Yeah. Yeah.

Guest 2

And along with, you know, authentication is the permissions. So maybe this user does exist. They're they're logged in. They have, rid they're they're authenticated as being they are who they say they are, but do they have access to do this thing? Are they have the proper role? Do they meet is their account verified or whatever the types of permissions you might have in place on on your server? It's important because, when we're working especially with databases, security by obscurity, in fact, they're just having an API endpoint that exists that can do operations on your database, Having it not locked down by some sort of permission system is not really an option. You you need to have permissions on your database to do anything. So In this layer, it kind of determines who can do what. What access do you get? Does this user have the proper rid. Role level to be able to do the operation.

Guest 2

And since this is being all taken place on the server side, right, typically, what happens here is a request comes in. You have what either is their their cookie or their session or any of that stuff. You pull in the user information, and all of this is taking place on the server. So it's not like it can be spoofed. The server is checking into the database. It's looking at the database, looking at that access role permission, and then acting as sort of like a bouncer Saying, Hey, you can come in or Hey, GTFO, get out of here. Yeah. It generally,

Wes Bos

every single request that comes in, rid. You will look up the currently logged in user. And that's I guess that's part of the authentication layer is that rid. When people sign up or sign in to your application, you authenticate them. You see if their password is correct, Or it can go a little bit deeper with things like third party login and OAuth and whatnot.

Wes Bos

And there's generally 2 ways to do that. Rid. There's JWT, JSON Web Tokens.

Wes Bos

Once they are logged in, you give them a little token and you say, Hey, rid. Anytime you want to query something or delete something totally cool, but make sure ready. Bring this token along. You know, you put it in their hand and whether you generally, that that JWT can come in any number of ways. Some people put them in cookies, some people put them in local storage and then send them along. Some people will It depends on the client as well. But generally, it's just like a little, like, here's my token. I'm good. I'm allowed to do these the following things. Rid. My mother said I could be here.

Wes Bos

Exactly. Mom said it was okay. Mom said it was okay. I'm allowed to query these movies.

Wes Bos

And then, there's also sorry. Go ahead.

Guest 2

Do do your kids are are they at that age where they're like, mom said it was okay, and then you're like, That's, Cornet, did you say this is okay? No.

Wes Bos

It's so classic. It's There we're at a point now where, rid. What some of our kids will say, like, mom said to ask you. And then I'd be like, Caitlin, did you say to ask me? They said I said no.

Guest 2

Rid.

Guest 2

Yeah. It just asks the other parent. How do kids come like, I remember a child and doing that exact same thing, but, like, How do kids come up with that that, like, it's just, like, innate that, like, kids just, like, decide that that's, like, what you do if one of the parents says no. The Thing you do is you just go after the other parent,

Wes Bos

or sometimes I'm just too exhausted to even even do it myself. Rid. Anyway, so there's that's JWT.

Wes Bos

There's also session based stuff.

Wes Bos

Session based stuff is generally browser only.

Wes Bos

So a lot of the newer APIs built in the last 5 or 6 years will use tokens instead because rid. You have an iOS app or you have a security camera. You have other stuff that needs to log in, and there's no no concept of sessions. As well as You talk about servers, the server implementation often with serverless and edge compute, Those things generally are run on different servers, so sessions gets a little bit more tricky there. So rid. Though that's the authentication layer, we talked about permissions layer.

Wes Bos

And then, like, what other layers do we have here? I have client layer, which is not really part of the API. But let's think, is there any other part of the API? Oh, like Interesting use cases like a photo and file upload that that's not part of CRUD. Well, it kind of is, but not really because rid. Generally, when you're doing, file upload, it's a little bit more involved. You have to have different special types of forms called multipart, Meaning that it it sends the data in multiple parts.

Wes Bos

Right? You have a large photo. You can't send that entire photo Over the wire in one go, so the browser is smart enough to upload it in chunks.

Wes Bos

So you have to be rid able to accept those chunks on the server side and and then do what you will with them. Send them off to them or resize them and send them back. It's kind of up to you. So that generally takes Some different stuff. Same with real time. If you want to have, streaming.

Wes Bos

Streaming or real time. What's the rid. I'm forgetting words. WebSockets. Why are I forgetting words for everything today? If you want to be able to do real time stuff rid. That is not generally covered by a REST API, because a REST API generally is you have a request, you send it, You get a response. That's it, right? Open and close. And streaming is generally you open it and you're listening for messages that come and close. And rid. That's a whole different world, but it can be still be part of your API. Yeah. Totally.

Guest 2

Yeah. And, man, some of this stuff's really wild. I remember making some mistakes when I was a younger developer. Like, I all I wanted to do is send an image to a service rid Or something like that where I had something I could have done client to that service or even I could have done a serverless function or something. Right? And And I was sending all of that information to my server, which then sent it to that server. And then you that's like if you can unload things onto the client, and not have to do them in your API on your your server side, then that's just another one of those use cases where we're often talking about, like, what would you use a serverless function 4 or, what types of things can you avoid, throwing into your API? You do have to be kind of considerate that when you're writing an API and you have a server here, rid. That server is is you know, it's gotta process these things, and it is just a computer somewhere running this stuff. So if you don't want to incur a bunch of performance, rid You know, crushing stuff. You can always look at doing something like a serverless function or whatever you can offload to the client is good for that too. Rid. Nowadays, we're getting all sorts of cool new things in the client side via Wasm. And who knows what? Where you can do all sorts of cool image manipulation stuff without sending it off to a server somewhere. It's rid. True. And also, they can like, one neat thing about GraphQL is you can do this thing called schema stitching,

Wes Bos

which means that rid. The actual work performed in the GraphQL API could live in 7 or 8 different servers. Right? That doesn't have to be on 1 single server, but it can be surfaced via 1 API.

Wes Bos

And then things like Cloudflare functions and Edge functions, Those things can also give you a single API endpoint, but divert the work to wherever it needs to happen instead.

Guest 2

Totally. Oh, we forgot the caching layer. You wanna talk about that? Yeah. Yeah. We talked about caching before we recorded, and then neither of us put in the notes. It was probably So I brought it up. There's also a caching layer on top of here too, which like, a caching layer can come in handy because if your server is doing the same thing over and over again and it's always returning rid the same information.

Guest 2

You can cache that information at at the API layer to say, like, this API will always return the same information. We use a caching, with our GraphQL API and, actually, that's a a positive of our GraphQL API is that caching is really super easy for it. You can cache based on resolver, And each resolver can have its own caching mechanism for how often that that gets saved, but you could store something like that into a, You know, a service like Redis, which is like an in memory kind of storage for information.

Topic 7 43:51

Caching layer of API

Guest 2

And instead of going to your whole rigmarole of having to query your database and take up that time. You can get really, really, really fast returns on information by caching things that are either accessed very frequently Or things that are always returning the same information no matter what. Like, for instance, we we we cache our user information so that it doesn't, Like, if you think about it every single time, request comes in and you wanna check that those users authentication roles, sure, you're gonna want to do that kind of stuff. But if If the user object hasn't changed, then you should be able to pull it from the cache easily enough, reference that stuff rather than having to hit the database each time. This is here. If you are building your 1st API, remember we talked about an API to add two numbers together.

Wes Bos

Yes. Rid. 2 plus 2? That's super resource intensive. You shouldn't have to My computer's on fire thinking about it. You're gonna that thing is gonna fall over.

Wes Bos

Rid. You're gonna you're gonna be broke.

Wes Bos

So what you could do is you could store 2 plus 2.

Wes Bos

You could say, well, the inputs are 22 rid. And the output is 4, so let me cache that result forever because math is not gonna change. I'm not gonna change. You will never rid to use your CPU to add those two numbers together again because you could cache them. So that'd be actually really fun. At the very least, you could cache it in memory, or you could store a database or or use something like Redis or literally anything. Yeah. Literally anything.

Guest 2

Cool.

Guest 2

You know what you could also use for literally anything? I I mean, as long as you're accepting and and and doing invoices, you could use FreshBooks. You're doing, what online accounting? The funny thing about accounting is basically anything, but anything that you're accepting money for or whatever. We all we all do money stuff. That's right. Yes. You'll wanna do all your money stuff with FreshBooks. Wes, do you wanna talk more about how you use FreshBooks?

Wes Bos

Billing and payments all in one place with FreshBooks. Rid. You create invoices. You can get paid on FreshBooks. It gets deposited right into your bank account. You can do all of your, invoices and expenses right inside of rid. FreshBooks, you can do time tracking. If you are running a small business and you need to keep your books in order, you should check out FreshBooks at freshbooks.comforward/ syntax rid. For a 30 day free trial. No credit card required. Thank you, FreshBooks, for sponsoring. Sick. Let's go real quick. Client layer. This is not really part of an API, but People are interested in it.

Wes Bos

In order to interact with your API, you generally need to do something in the browser or in your app.

Wes Bos

And at the very basic, you can just use a fetch request and send it over. Even if it's a GraphQL API, You can still query GraphQL without having a fancy package because GraphQL just needs a string At the end of the day, that is formatted in a certain way.

Wes Bos

But then once it gets a little bit more in-depth, you can get things like React Query, Apollo client. In the thing. They'll do caching on the client side for you, which is really nice.

Wes Bos

Generally, if you visit a website that is very snappy and whatnot. They will be caching that data in the browser. Somewhere. Yeah. Somewhere generally in the browser. So that Local storage. Local score. You got it. What's the database that's in the browser? IndexedDB.

Wes Bos

IndexedDB. Yeah. So that's the client. There's tons of them out there. We're not gonna go through all of them. That's probably its own show, but that's what you can do. Totally.

Guest 2

Cool. Well, that, I think, just about covers it. Oh, no. Wait. We have also some,

Topic 8 47:55

Client layer of API

Wes Bos

Yeah. Should we should we talk about this? This is we we get questions about this in the Pollock all the time. Should I use x or x? Service.

Share