YTread Logo
YTread Logo

APIs for Beginners - How to use an API (Full Course / Tutorial)

May 30, 2021
- Hello, I'm Craig and I'm a developer. In this


we will explore a term that you have probably heard quite a bit. That term is API or application programming interface. In addition to being able to recite what it means, when you complete this


, you will be able to analyze what an API does, understand why it exists, and be able to list the many benefits they provide. You'll even get hands-on experience using some popular web APIs that will give you an idea of ​​what all the excitement is about. We'll start from the beginning, so I don't really expect you to know much before starting this course.
apis for beginners   how to use an api full course tutorial
I would like to request that you have a little bit of coding experience and a little bit of web knowledge. If you've written any program, even your typical first program, do you remember the one where you type the words hello world? If you've done that in any programming language, you'll be pretty much ready for this course. It will help you to have a basic understanding of how the web works with web servers and browsers, but don't worry. We'll touch on this too. Now, if you haven't met these requirements yet, check out the notes attached to this video to see where to start with some programming and web basics.
apis for beginners   how to use an api full course tutorial

More Interesting Facts About,

apis for beginners how to use an api full course tutorial...

Oh, that reminds me that you should probably take some time to get used to your learning environment. The notes I just mentioned are attached to this video. I'll also post more information in that section to keep you updated on what might have changed since the time I recorded this. Now I'll do my best to remind you to look there when there's something I think you should see, but you should really get into the habit of checking that area. There will be tons of juicy information there. These videos now have subtitles, so if you think you could benefit from having them, use them.
apis for beginners   how to use an api full course tutorial
This space is all yours. If you want me to talk slower, use the speed controls to slow down, and if you know I'm taking too long, just speed up! I'm a pretty good squirrel, and last but not least, take advantage of the fact that you're in a video course. If you need a repeat, use the video controls to rewind. If you feel like you need a break to take something in, please pause. I'll be right here waiting for you. I know I have picked up bad habits from watching videos with all streaming media. Now, while binge-watching can be a great way to consume an entire season of your favorite show, it's not the best way to learn something new.
apis for beginners   how to use an api full course tutorial
Education is not meant to be a binge, and because of this I will probably remind you quite a bit to take breaks and encourage you to let what you have just learned soak in. Alright, let's get to it. API, those three little letters create quite a stir, don't they? Now, first, I would like to take some time to clearly break down what is meant by application programming interface. By understanding its purpose and a touch of its history, I believe you will begin to see its importance and understand why this term keeps coming up in your life.
Once we have a good understanding of the what and why of APIs, we will go and learn how to explore the existing ones. We will get familiar with a useful tool, Postman, which provides a good way to interact with web-based APIs. We'll use that tool to access an external web API to send real text messages and get some interesting data from a music streaming service API. After some practice with the APIs, we'll embed them in a web application. The application we are going to create is a web application called Complimenter. Our app will allow you to send compliments to your friends, family, and colleagues via text messages, and then encourage them to visit your site and do the same.
I've now included the final applications in both JavaScript and Python, and together we'll look at how to use external web APIs to solve the missing pieces. In this course we will strictly use API. We won't write ours now. Well, now you will most likely end up learning some best practices in API design; we won't cover that specifically. There are many great courses available that show the creation thought process and I've linked some of my favorites in the notes attached to this video. In my opinion, the best way to start learning about any acronym is to focus on each individual letter.
For API, I think we should start with the last character, interface I. Let's talk a little about the interfaces you've already seen. Interfaces are all around us. For example, this radio here has a familiar interface. The interface allows me to do things like change the volume, change the station, I can turn it off and on. I literally have no idea how everything inside this works, but the interface still allows me to control the way it works through the options that are exposed. The magic that is happening is completely abstracted from me, and I am still in control of what has been determined, which I, a user, can handle.
Interfaces often evolve over time, such as a clock radio. It has my familiar volume and station controls, and also adds some new features like changing the time and setting the alarm. I still have no idea how this works implementation-wise, but the interface is something I can generally understand, and as technology evolves and new options appear, they make their way into new versions of the interface. It still abstracts things away for us, but it allows us to be in control of new features. Sometimes these physical interfaces become so recognizable that they even make their way into GUIs.
Did you find out that? There it is again, sticky or GUI, graphical user interface. This is my music streaming app on my phone, and there's my familiar play button in the user interface, or UI, and I know what that play button does when I press it, but I have no idea how it does it, and I agree with that level of abstraction. I even depend on it. What would you do on public transport without music? Do you like talking to people? Hello how are you doing? Now the developer who wrote this music streaming app understands how the play button works.
He coded the button so that when you click it, the music starts playing. But here's the thing. Our developer is also working with quite a few interfaces that abstract away some of the details. For example, you wrote some code that occurs when the button is clicked. He probably did it using an event handler on the button. However, what he didn't have to do was write the code that makes the button interact and change when pressed. You didn't have to write the code that produces that familiar click. It was already there for her. In fact, buttons are an interface.
They provide the developer with the means to control their interactions and at the same time abstract away how that works in terms of implementation. This button is part of the API, or application programming interface, that is available in the application framework that was used to create the application. Because most of the applications need buttons, this interface has been created to help our application developer or programmer to use it. Now, by implementing the button interface, our developer was able to make his code run when the button was clicked. It's worth noting that the code probably also uses a media player API provided by the device's operating system like Android or iOS.
This media player API eliminates the need to understand the details of how to send audio data to the hardware. The developer knows that he only wants to call the play method of the media player API and I assume that the song is not stored on the device. It is being transmitted over the network, so a web-based API call was made over the Internet to get the data. In reality, they are APIs down to ones and zeros that provide abstractions at many levels. Let's take a look at what all of these interfaces have in common. They all define ways for us to interact or communicate with an object, whether physical or software, and as a user of the interface, we do not need to understand the implementation.
We don't need to know how it works. We just need to know what we have been allowed to change or see. Interfaces abstract the implementation. Now, while the UI, or user interface, is made for the user of the application, the API is made for the application programmer to use and extend in their applications with what I covered in our API, let's take a look. deeper look at the rest. of the acronym API. An API is a kind of contract, it defines how it is expected to be used and defines what you can expect to receive from using it.
Think of it as a set of tools designed for software developers like you. An API is created to help make your life easier by giving you access to the data and giving you an abstraction of the implementation. You know, not needing to know how he's doing whatever he's doing. They save you from having to create everything yourself. When designed well, they make almost impossible things happen, in just a few lines of code. You're probably starting to see why it's important to get familiar with them, right? I want to give a quick warning about some naming problems you'll probably run into.
Today, the term API is almost always used as a way to explain web-based APIs. In fact, it's probably safe to assume that when you hear APIs in the wild, chances are people are talking about a web-based API. Now we will explore them here in a few. However, if we focus on all types of APIs instead of just the web-based subset, we'll get a better look at why web-based APIs are so popular, so hold on, we're getting there. APIs are everywhere in your software journey, virtually everywhere you look. Your programming language, whatever it is, provides many APIs.
Let's look at one that is common to all of them. They all provide some way to work with strings, you know, as a series of characters. Do you want to make your textile capital letter? Just call the API method and voila, you could probably create that uppercase string yourself by doing some kind of low-level bit calculation on each character, but you don't need to, because your programming language has abstracted it for you. and provided a useful string API. It exists because this is a fairly common problem that developers encounter, because these programming language specifications are just interfaces, different operating systems can provide their own implementations to make the code work correctly in their environment.
I think an easy way to imagine this is to think about how different operating systems, like Windows or Mac OS, maintain their files. They are totally different, but their programming language provides a single API to work with the file system. You can write a script and it works on Mac or Windows. It's the implementation that takes care of all the details for you. Very good, right? Definitely something to be grateful for. It makes our lives much easier by not having to worry about the operating system being used. The importance of an API for a language cannot be underestimated.
There have been some fascinating legal cases questioning whether the language API itself, and not the implementation, can be copyrighted. See the notes for more information on this. Similarly, there are different web browsers, such as Google Chrome, Microsoft Edge, Safari, Firefox and Brave. You may not have thought about this before, but isn't it amazing that you can write code for the web and have it work on any web? Now this works because there is a set of web APIs that all web browsers must implement in order to make that magic happen for you. We stand on the shoulders of giants.
We really should thank those giants more often. There are library authors and maintainers who package code and solve common problems so you don't have to do it yourself. For example, do you know how to programmatically make a black and white photo? I don't want to say either, but I can download an important image package into my app and suddenly I can do it. I just call up a method and boom, I wish real life skills worked this way. I would import the dancing to make it more fun at weddings, cha cha cha. Frameworks provide an API that allows you to extend what has been provided to make it your own.
Like for example, most of the web frameworks provide you the facility to add a new route to your web application. It allows you to write dynamic data to a template that you specify and does all this with just a few lines of code. You don't need to understand how things are done, but you do need to know how to write an implementation based on what the framework expects. In this case, you are using the API, the contract to write a valid implementation that meets the requirements. All of these APIs we just talked about are local to our codebase.
They exist within our code. We use them to avoidrecreate the wheel. That is, they help us perform the tasks we need to perform by abstracting a large amount of work from us. The things we developers shouldn't worry about. We should focus on the business problem at hand, and that means a big part of your job is figuring out how to leverage these APIs to your benefit. Now I think it's a great time to take a short break. I gave you a lot to think about and I would like you to take a minute to breathe. Why don't you write down some APIs you used today, even if you weren't coding?
I know you've seen some in action. If you're having trouble thinking of any, I'll give you a hint. You are watching a video right now within a web browser. When we return, we'll explore the concept of remote APIs, those that don't run locally in our codebase, and why it's such a powerful concept. (relaxing electronic music) It took me a while to find this remote control. It was on the couch. He's always on the couch. Anyway, this remote control has an interface, right? There is the power button and there is a channel changer, and when I press the volume button, it sends my request to my device and the volume changes as if I turned it up using the interface of the device itself, and we know why. that is important.
I want to remotely control my device. I don't want to get off the couch. Of course, there are more or less vague reasons why you might want to control objects remotely. This cute little robot, for example, has a remote API. You can send it commands and it responds. It even sends sensor information. These traffic signs can change based on an API call. This drone here is actually controlled remotely by an app on my phone. See? It's not just physical objects that benefit from remote APIs. We often don't have space on our local machines for all the available data.
For example, have you ever used one of those apps that helps you figure out what song you're planning? You send a snippet of a song you heard at a grocery store using your microphone and it sends you back exactly what the song is. It's usually Phil Collins. It turns out that both grocery stores, and yours truly, love Phil Collins. You don't have room for all the songs in the world on your phone, and with this remote API, you don't need to have them all. It does all the searching and processing, and it's surprisingly fast. How is it possible for him to do that?
I don't know, but I love the interface. It's so fast. There is another benefit of remote APIs: computational power. Because an API removes the limitations of your local machine, you can gain access to seemingly infinite amounts of power. A good example of this is the Google Translate AR application. You can use your phone's camera and, almost in real time, it can be translated directly to your screen, instantly. A lot of processing power is being used to make this magic happen, and that processing is being done elsewhere. (speaks in a foreign language) It took quite a bit of experimentation and some evolution of ideas, but over time we finally turned this remote API dream into a reality.
Now, I'm going to leave a little history in the professor's notes, but I just want you to know that the struggle to achieve this concept of remote APIs was very real, but the biggest part of the problem was that there was no standard that everyone loved. Things were pretty complicated for a while while ideas were being discovered, but then it happened. A new architectural style came along that was clear and allowed us developers to interact with specific resources over the web, and it literally changed everything. This style quickly emerged as a winner, and almost everyone started offering and consuming APIs over the Internet, and what I'm talking about here is REST or Representational State Transfer.
It was the approach we needed and, honestly, it's the abstraction we developers deserved. As we already mentioned, the popularity of REST is spreading very quickly. It almost completely surpassed the term API. It's like when we use the word Xerox to mean photocopy, even though Xerox is just a brand of photocopiers. I think Xerox does other things too. That's how ubiquitous REST is. REST is surely not the end-all be-all of remote APIs. There are definitely some limitations, which we'll discuss here in a moment. Technology is constantly evolving and of course there are movements that are still advancing the concept of better remote APIs, some terms you may have even heard, such as GraphQL.
More about this in the teacher's notes. For the rest of this course, we will delve into APIs written in the REST style. When APIs adopt the REST style and restrictions, they are said to be RESTful. Beautiful, right? If you feel like you need a little rest, go ahead and pause before delving into what it means to be RESTED. Sorry, that was a bad and obvious joke, and as a developer you have to do it, you really have no choice, and since REST is at the pinnacle of web technologies, we should probably do a quick refresher on how the web works. (relaxing electronic music) It may have been a while since you thought about how the web works.
There are a few terms I'd like to reload into your working memory before talking more about how REST uses them. So let's use the web. I have my computer here and on it I have an Internet browser. This browser is a web client and I will use it to connect to a server. I'm going to do this by putting a location in the address bar, a universal resource locator or URL to be exact. You may also hear this referred to by a superset term URI or Universal Resource Identifier. Now our URL here has a schema part, and this happens to be HTTP.
HTTP stands for Hypertext Transfer Protocol. Let's break that down a bit. Let's take that last part, the protocol. A protocol is also often compared to a contract. It's a bit lower level than an API, but is similar in concept. You can think of it as setting expectations for how to communicate. An example that I think sticks in my mind is if you've ever been to a rally and someone sings one of those chants where they go, when I say food, you say bar, food bar, food bar, here, let's do one. When I say H-T-T, you say P!
HTT, HTT. I just realized that maybe I made you scream pee out loud. I hope you're in a coffee shop, that would be awkward. Anyway, we, you and I just established a very quick protocol. I told you how to respond to my specific request, you would have been breaking our agreed protocol if you had yelled anything else, but Q. So the browser creates an HTTP request for you. Along with the URI, it also specifies a particular HTTP verb. In this case, the verb GET is used, which is used to clarify that this request will only receive data.
That is, it will not make any changes. The server receives the request that was transferred from the client. There's that second T. The server then does the work it needs to and finally generates the resulting web page and sends a response to the client, my browser in this case. Now, the most important part of that response is the body. For a web page that contains the HTML, or Hypertext Markup Language, which gives us the rest of the parts, the HT of our acronym. Hypertext is text that can be linked to other texts. In HTML, we make that link with anchor tags.
So with that response, the browser displays the page. When one of those links is clicked, a new HTTP GET request is initiated and the process repeats over and over again. Between those clicks, the protocol is carried out. We made the request, we got the answer. HTTP, as originally designed, is a stateless protocol. Once that request receives a response, everything will be done. If you want to maintain some kind of state, your client will have to manage it itself and set it with each new request. See the notes for more information on this. There are more HTTP verbs, also known as request methods, than just GET.
The most common scenario you see is when you find a form being used to take information from you; You will typically see the verb post used to explain that you are sending or posting data to the server. Okay, so our protocol that is used to transfer this hypertext is certainly a little more complex than our rally chant. There is quite a bit of important information included in both the request and response. You've probably seen query string parameters and URLs. You know, what comes after the question mark? This is a way to pass information about the request.
Another common way to convey this information is through specific key-value pairs, called headers. Both requests and responses have headers and are used to help better communicate what is wanted and what has been returned. Now, some of the popular request headers allow you to specify information about the content that you would expect, such as language or content type. You can also indicate that you only want a page if it has changed since a certain time. This technique allows for caching, which is a powerful concept. Why get the


page if you already have it in your local cache?
You can embed authentication information in each request using a header. This way you basically keep your client logged in on all requests. The response also contains headers. A very important one is the status code. This lets you know what happened on the server side and can convey things like missing documents. I'm sure you've seen the old 404 error. The page has been moved or, hope


y, everything is fine. A, 200. It can also explain the type of content, the size of the data returned, and much more. Ok I have it? Are you feeling good about that little whirlwind tour?
Remember, feel free to make me repeat myself if that was too much. I totally understand it. That was a lot of information. It's important to have a basic understanding of these things, because REST sits on top of them. It uses concepts introduced with the web to expose resources that can be accessed and manipulated. Let's take a look at how the RESTful approach leverages the web and its tools to your benefit and profit. REST stands for Representational State Transfer. APIs that comply with REST architectural style restrictions are considered RESTful. A typical way to teach about RESTful APIs is to cover the constraints that define everything from the beginning.
I don't know about you, but I personally find approaching learning that way quite overwhelming, especially early on. I mean, we haven't even looked at an API yet, and furthermore, most REST APIs you use will comply with all of these restrictions. So here's the thing: I promise we'll go over all the limitations, but let's do it on our own time. How not to learn them all, right now. We can even turn it into a fun journey like a RESTful constrained scavenger hunt, complete with prizes. These are the governing architectural constraints necessary for an API to be considered RESTful.
We'll mark them up as we go through them and then we'll come back one more time at the end and review them. I have to collect them all. Sounds like fun? Good. Let's start by talking about how REST APIs sit on top of web technology, like a little hat. Just like on the web, the client makes a request to a server. The client in this case will usually be the program itself and will probably use some type of library to create the request to the server. The protocol used is, as you may have guessed, HTTP and is stateless.
The server will not remember anything about the particular client. If you want to maintain a state like your login data, you need to send it with each and every request, and you'll do that using headers, and so, we've talked about two of our REST constraints, Client-Server. Architecture and statelessness. You've already been knocked down by two. You're on a roll now. We should probably talk about what that request asked for, right? Well, I was probably asking about a resource. A resource is a bit abstract and that's intentional. It's the R in the URL, or URI, we use the term resource to refer to an object, which is also quite abstract, right?
This is because we can use resources to describe almost anything we build. For example, let's imagine the website of an e-book store. On the home page, perhaps there is a list or collection of new books. Each of these books is a resource, and we click on it to take a closer look at the book's resource and see a link to the author, who is also a resource. We click on the author's resource and see a collection of all the other books they have written. Maybe we'll even see a group of fans. Again, another collection, and every one of those fans is a resource.
By clicking on a fan resource, we can see the collection of your favorite authors and books. Everything is a resource. Let's change gears. How about an application to share images on our phone? So we have user resources. Those users post photos, which are resources, and photos can be loved. So there is a resourcefor lovers. Maybe there is an album that can be created and there is an album resource that contains photo resources and the albums have a collection of resources for contributors. It turns out that almost everything we want to build can be expressed in terms of resources and collections.
Most of what we want our applications to be able to do with their resources can be expressed through the unfortunate acronym CRUD, which stands for Create, Read, Update and Delete. Now, as a user of the ebook site, all we did was read a bunch, no pun intended. Actually, that was my intention. We were reading, right? We simply make the information display as if we were recovering the author page. We made a read request for that page. The web browser used a GET request for that specific author page. Now the RESTful API follows the same logic. Your program sends a GET request to a URI.
Then the survey response with data and of course all the HTTP headers you know and love, and the body is usually represented these days as JSON or JavaScript Object Notation. Now, JSON provides a great way to structure and nest your data. Every programming language I can think of provides some means of converting a JSON string to a native object. The content type is usually something you can specify in your request if JSON isn't your thing. Now, if you remember, there are other HTTP verbs available. These verbs are used in REST APIs to clearly indicate the intent of your request.
Do you want to add an author? Publish to /authors and submit the data you want to update in the body of your request. These fields will be defined for you somewhere. Do you want to delete an author? Send a takedown to that specific author. Updates generally support the patch verb and you will see that we can represent CRUD, Create, Read, Update and Delete using HTTP methods. Very good, right? What this means is that you can interact with any application that has its REST API exposed. You could capture data, automate tasks remotely, and even combine services. This is called a mashup, and here's the thing: there are tons of APIs available for almost anything you can imagine, and if they are truly RESTful, they will all feel more or less the same.
You can build anything. There are services that allow you to do amazing things with a few simple API calls. So now the question is: what are you going to build? Why don't you take a short break and when you come back, let's explore a RESTful API together. We'll take a look at how to use the music streaming service Spotify and its excellent RESTful API. (relaxing electronic music) You have a new understanding of how web-based APIs work. I'll quickly walk you through some imaginary REST APIs and now I think it's time for us to get a little more specific.
Why don't we go exploring together? Now, some of these REST APIs allow you to try them out from the comfort of your own web browser, and one of my personal favorites that allows for exploration is the music streaming service Spotify. So here I am at and a quick warning: this is bound to look different. By the time you get here, there will be teams of people working on the site to improve it, and you will have the benefit of a better website than the one I have right now. So, just a reminder, you should check the notes attached to this video for any breaking changes, and if you don't have a Spotify account yet, don't worry.
As you can see, it's free and that same user that you can create, you can end up using for development purposes. So let's say you didn't know Spotify had an API. Now what I usually do is look around me. Typically, most sites store the nerdy stuff here in the footer. Here we go. Developers, that's what we're looking for. It is a community of developers. That's us, let's do it. Wow, I love a site that treats me well, even as a developer. This is really cute, right? So you can do a lot of things since I was last here, let's take a look from the front.
So, audio analysis, wow, you can learn about the ability to dance, maybe I can install that skill after all. Oh great, audio playback. So, it's a nice thing: you can insert a player right there. You can put a player in your app, an SDK here, which stands for Software Development Kit, and we'll look at one of those here in a moment, but basically what it does is give you an API that integrates with other APIs. , and you will feel native to your programming language. Great, and then let's take a look here at the recommendations. Oh, incredible.
It will give you specific recommendations. Awesome, this is great. Dance ability target, I'll be able to dance and see this JavaScript here, it's doing a GET to one of its endpoints. Impressive, this looks good. So let's take a look at the top here. Let's go ahead and figure out that's what we're trying to do. We're trying to figure out what we're going to do with this API. So let's click here and this will give us some ideas of what we can do. We'll see. Real applications that integrate audio functions. This is incredible. I love when sites do this.
I think it's a great way to get inspired if you don't already have an idea of ​​how you could use the API. You can see how other people have used it. Great, this is the audio analysis we had seen, a quick panel of audio characteristics of the songs, and again there is that possibility to dance. Here is the reproduction, so you can get a player. This is super interesting and these are applications that use them. iPhone app, listening room, Runkeeper. As you can see here, this is for iOS and this is for Android based phones. So iOS is like Mac-based products, and these are Android-based products, and these are widgets.
I'm not exactly sure what that is. I guess those are the HTML widgets we had seen, and that's cool, right? Because it is a web-based API, all we need to do is connect to it over HTTP. Then any of these devices can connect to it. Quite skillful. Alright, let's move on. So we have recommendations. Brilliant. I always need music recommendations. Look, oh, that's good. Actually, it seems like a good place to start, right? And if we were to go and look for different things, then there are six degrees of Kanye West, I guess a lot of people are connected to him.
Find other artists who are like the artists you like, this is great. Why don't you say we look at some of the documentation for the search? So I'll click on this and read the docs. Let's read the documents. Oh well, you may not see this, but there is a new Web API reference in beta, which means it's not ready for everyone, but it is ready for people to try. I'm going to go see that. You may be there and out of the beta period when you see this. Well, let's take a look and see about this search API.
Let's see, Search API. So let's move on. Let's click there. As you use more and more APIs, you'll become familiar with reference documentation like this. This explains the contract of what we need to do to use this API. So you'll see here that there are different parts. So this is the request that we're going to send, and here it says this is a header, and it says whether things are necessary or not, and this is indeed necessary. So this is the authorization here. There is a header that is required in the authorization request. Authorization means that you know what you are allowed or authorized to do.
Spotify and many other APS use the concept of access tokens. So, that's a header, that's the required header, and here we see this query parameter, right? So check the parameters and you'll see that this one requires this queue. So this is the search query, the keywords, right? So here's an example of what it is, and this shows you that it should be URL encoded. There are a few more notes on this here in the snippet. So no, we have that the queue is required, and also the type is required, and the type is like album, artist, playlist, like the type of resource that is available in the Spotify API, and if we continue scrolling down , there is more, there is more. optional query parameters that are available.
It really helps you specify your search, they have a very rich API, and then it shows you this response. So this is what's coming back. Then you will see that you will get a header and the status code, very important. We'll say 200 okay. If it is good in success rate. On success I will say 200 ok and the response body contains an array. So like a list of artists, objects, or album, artist, whatever type you were looking for, it's going to be in JSON format, just like we talked about JavaScript object notation. And then you'll see that when there is an error, there will be an error code and the body will have the error message, and then there are some more notes here, which are really comprehensive.
This is great. So in the code spaces, that's what we saw. We saw that %20. It's about making sure you can't use a space; otherwise the URL will be broken. This is how you do that. You will see that there is a lot of different information here. Yes, you can use Asterix and show you all kinds of ways to do fun queries. Let's go ahead and test this in the web console. He's quite skilled. So what this does is it allows us to search for an element and shows us how it works. You are doing a GET and some authentication is required.
So we'll need to build something here, but you'll see here that it shows what it's doing. It's doing a GET to this URL, and this is the code that will actually run, and you'll see how we change the fields here. So I'm going to change this to a very popular artist in my house, Lizzo, and you'll see that it's updated here. Updated my query and the type is now set to artist. Okay, and we have this OAuth token that we need to get. So we need to get this token. So again, what are they allowed to do?
So we're going to choose Get Token and it tells us that this specific endpoint does not require any specific scope. These are areas that you can do. So when you build this token, you say that to use this key, these are the things that people can do and we don't need to do anything specific for this. So let's go ahead and not review any of these. We don't need to modify a private playlist, we don't need to. So we're going to do Request Token, and here it's going to ask us to log into Spotify, and if you have Spotify, go ahead and log in, and if you don't remember, it's free, you can just come. here and register.
And we can put our emails here. So I'm going to put mine in and here's a little trick. If you don't already know, I'll put up an API course. Let's make an API course like [email protected]. My email address is [email protected], but if you put a little plus here, you can categorize things on your own. So just a little trick, and that way if you're worried about emails coming in, you'll know they're coming from that address. I'm going to put the password on my luggage, which is one, two, three, four, five, just kidding.
What should we call you? I love it when you call me big daddy. Okay, so my birth date is November 19th and I was born in the wonderful year 2000, just kidding. This is amazing. I love this Spotify. Thank you for being inclusive, inclusion matters. I'm going to choose Man. I don't want to share my registration details and I'm not a robot. I promise. I think I'm not a robot. Identify pedestrian crossings. What's that? Alright, there's one that's definitely a pedestrian crossing. That's a pedestrian crossing. I mean, I could cross the street here, I could. Very good, I passed.
I am not a robot. I'm going to click Register. Here we go. I'm going to save that password. What happens if I activate synchronization? Everyone logged in as Big Papa. Here we go. So I'm going to click OK. I'm going to go back to the page and you'll see that it's now complete. Now, one thing I want to point out here is that my token here, my key is on the screen, and if a hacker were to pause my screen and copy it, they could essentially do things to my account on my behalf. but of course I know this and I will delete this token later.
Remember this is like leaving your car keys in the driver's seat. You probably don't do that. So treat these keys the same and keep them safe and with you. So I could copy this entire command and paste it into my terminal, and it would work. We'll do that in a moment, but what I want to show you first is that you can do this, the Try It button here, and what happens is what comes back is this beautiful JSON. So you'll see that what's returned here is like artists, and it's an object that has the search that we created, and then here are these elements, and you'll see that it's an array, because there could be multiple artists named.
Lizzo, and I guess it seems like maybe there is. Yes, it seems there is actually another artist named Lizzo, popularity 88, and what is Lizzo's popularity? Is your genre Escape Room? Man, I feel old. One thing we can do is look and see if there are these external images so thatus. Now you'll notice that the message says that you might not notice that the status here says queued, but if we go and look at our message log and run this again, we can see that they were sent. For Postman, there's our emoji. And here's more information, and if we scroll down a little bit more, we'll see these subresource URIs and now we can see this media that was submitted.
So let's go ahead and I'll click on this link and watch what it does. It will make new GET requests. Now there is a little problem, because this GET request is outside our collection. Usually when I need to do something like this, there's a little trick you can do to get the authentication information. So let's just click Save, and I'll just call it, you can call it that if you want, and then I'll call it temporary, because we'll delete it when we're done here. So we'll call it Temp. Tell that to SMS, and when we run this, we'll see that we got the media list and because you can send multiple, right?
You can send several images in one, and we will see here that there is an official one, and we will see what the accounts are like, and then the messages, and then the media there. There are sub-resources. So I'm going to go ahead and click on that. And if we wanted to, we could run this request, and it would show information about the media, but if you actually delete this .JSON, it will show the form of any media. So we'll make this request and see what happens. Let's see, we recovered my GIF that I sent. And with a request this size, we probably don't want to do it again if we don't have to.
So this sounds like the job for client-side caching. Well, let's see if our API supports caching tricks. So what I'll do is wait for the headers that are in this response. Okay, so you have this last modified header here, which is a good sign that it supports caching. So let's go ahead and copy this value. So I'm going to copy this date here to the clipboard, and if I go up to where my request was made, if I go into the headers here, I can add a new header, and I'll say if and you. You'll see that Postman is doing a very good job of showing you what's available.
So if it's been modified since then, because this is basically what his client would do, right? He says, if this has been changed since then, show it to anyone, otherwise don't do it. That's what he does. So I go in and I go ahead and I'll click Submit and you'll see my API came back unchanged this time. So our API supports caching, which ding, ding, ding, means we cover another part of the RESTful API restrictions using standard HTTP caching mechanisms like last modified and etags, a RESTful API should support caching. cached. It's up to you to maintain the cache on your client and decorate your request, but this can be very useful to avoid making unnecessary requests.
Great, so let's make sure we have them saved. See these little orange dots here? It means they have not been saved. So I'll click on it and click Command+S or Control+S, and I don't really care about the temperature, and I don't really care about this one. That was just kind of an exploration. So let's take a look here. We have this temperature, we can choose and say Delete, and we will remove it from the temperature, and now it has this, it has our message and our creation message. One more thing before we finish. I wanted to show you that you can actually generate code from this.
So if you click here, you can see here is an example of how to generate a code snippet. It will actually run the code and configure everything you need to run this code. Now there are things called helper libraries that do this, and Twilio has one, and we'll get to it here in a second, but it's pretty nifty, right? Really, really powerful, and you just copy it to the clipboard and boom. Pretty powerful, huh? Awesome job diving into Postman. It's a super powerful tool and it gets better every day. There are so many features that we don't even cover.
We barely scratched the surface. See the notes for where to get more information. We saw how to organize our requests into collections and how to share common, safe values ​​by using variables. We learned how to add different values ​​to your requests, both in form, values ​​and headers, and we also saw how to navigate through various sub-resources by clicking on URIs. We even saw how to create actual executable code from your request. While we were in the Twilio documentation, you may have noticed the code examples on the screen. On that page, it is possible to select from various language implementations and solutions.
Many products offer what is known as an SDK, software development kit, or auxiliary library that allows you to interact with their product in your native language. As you can see, it completely abstracts the REST API. Next, let's take a look at the Twilio Helper Library. Before that, just a quick reminder to make sure you review the notes for this video. There is a link to a repository of created collections that are ready for use. There are many great APIs to practice with. Postman and Curl are great tools for accessing and exploring APIs. However, when the time comes, you will most likely need to write some code.
As we saw in Postman, you can actually generate code. All programming languages ​​come with some kind of way to make requests, and as you know, HTTP requests are all we really need to interact with REST APIs. Now, writing that type of code is totally fine, but you will find that you will end up writing a lot of what is known as boilerplate code. Now, by boilerplate text I mean code that is repetitive and almost always the same with just a few tweaks. Many products and services have created a solution to help you avoid this problem. They are often called helper libraries or SDKs, software development kits.
They will be specific to your programming language. These libraries help make your code more concise and readable. They usually also provide additional documentation for their editor, which I find very helpful. Let's take a look at some of these helper libraries. Let's explore JavaScript and the Python helper library. To do that, I would like to make sure you have Node and Python installed on the computer. I've put installation instructions in the notes. Let's start with Node. So I'm going to open the terminal on my Mac and I'm going to create a directory called scratch and I'm going to switch to that directory and here I want to create a directory called JavaScript and I'm going to CDN to that directory and I'm going to open my editor in this directory here.
So let's say code. I am using Visual Studio code. So we're going to open up Visual Studio Code and here in our directory, I'm going to add a new file and I'm going to call it just explore.js. Alright, now what I'm going to do is install the library in Node Land called NPM. So I'm going to open up a little terminal here in Visual Studio Code and run NPM and install Twilio. And that will come out, and it will get the library so I can use it, and I can use it like this now, now I can say const Twilio Goals requires Twilio.
And then we will initialize it. So we'll say constant client is the same as new Twilio and as you can see, it requires an account SID and an auth token, and I have those available here. Here is the SID of my account. I'll copy it and then we'll create the authentication token. Alright, then we'll put that in, awesome. Now, can you think of anything wrong with doing that by putting my account SID and auth token in there? Well, right now this is on my machine, but if I uploaded it or shared it with someone, my credentials would be there waiting for someone to steal them.
The typical solution here is to use environment variables, and we will do this when we build our application, but this is just a friendly reminder. Be careful with the keys. What we're going to go over here may be overwhelming, but someday it will make sense if you stick with it. I promise, oh, I've added notes, but really don't let this stress you out. The reason I talk about this behavior is because Twilio's JavaScript client works like most JavaScript libraries. It is asynchronous and is based on a concept called promises. So the way promises work is that you set up handlers for when the method call actually completes.
So to get our message log, we use this method. There's a method called, so we do client.messages.list, and what that method returns is an object called a promise. It is a promise of future value. The future value in this case will be our messages. So promises have an important method, and it's called then. So I'm going to go ahead and chain that message. I'll say .then, and this method should be given a function that accepts value. So I'll pass it a function. Now, in modern JavaScript you can use what are known as thick arrow functions.
So what I'm going to do is put in the name of the value, and the value here is messages, right? Because this is what I expect to be returned, and then I'll put in a thick arrow, which is an equals greater than sign, and then I'll put in the body of the function. So let's just log out of the most recent message. Okay, so we'll do a console.log and I'll use reverse ticks so we can get a string interpolation, and I want it to be the first one in the array. So we're going to say the most recent message is the dollar sign, messages with braces, zero, because it's in array.body, and that's a long row, this happens quite a bit.
Typically what we do is when we make this string, we press Enter here and we put it on its own line, still quite long off the screen, and if I ask you to format this with sentence, let's see what it does. . Here we go. Let's see, you know, he's done a good job bringing things together. So, and again, just to show you that this runs asynchronously, I'm going to make this call next, right? So this is, it looks like it was after the calls were made. Well, after you make that call, that call will be asynchronous.
I'm going to say collect your message log. So let's go over it real quick. What is happening here is that we are contacting the client and we are setting up a new client so that all requests made against this client are authenticated, right? That is the SID of our account and our authentication token. And then we'll use the client, we'll use the messages that are there, we'll make a list, and that list is an asynchronous method. Now, while this has been abstracting, we know what it's doing. It's making the same GET request that we did in Postman and Curl, and we know it will return a JSON response, but since this is asynchronous, it will immediately move to the next line.
It will say collect your message log, and when that call returns to the list, it will run this function and pass the return value of that response here. Now you should keep in mind that the return value here is a real object. It is not a JSON response. That clever little Auxiliary Library of ours has also abstracted that from us. It took that HTTP response, which has a JSON body and automatically converted it to an object for us, and you can see here it's an array of objects, right? So that's at zero, okay, so let's run it.
So I'll clarify it here and we'll say Node explore.js. So we should see the collection, or message log, and then the most recent message, fingers crossed. Here we go. Awesome. Yes, good. Now, one thing we need to make sure to do here is capture any errors that may have occurred asynchronously; right now, if an error occurs, it will be swallowed. Well, actually, let me show you what that means. This bites me all the time and I don't want it to bite you. Let's say you accidentally trimmed the last character here, mine seven. Let's get the last one out of here.
So I'm going to do that. So it's an invalid SID, I'll save it, run it, and it will say collecting its message log, and then it will end with no error, no nothing, but the results never came back. So what we need to do is detect any errors that may occur. Every promise has a method called catch, and what may not be clear here is that this then here, that is returning. Actually, this is also a promise. So I can chain here. So I can say .catch, and I'll catch an error, and again, thick arrow function, and we'll just log that error.
So I'll say console.error.E-R-R. Okay, now that we have it, it will chain itself and if something happens, it will send the error. So let's try it again. Let's see what happens now with our capture in place. Awesome. It tells us that it was not found, because that is wrong, right? Excellent. This is probably a good time to remind you if there's too much information you can, and you should probably delete the video and watch me do it again. I guarantee you'll catch some things you missed the first time, and at the very least, you'll see a dad joke I made at the beginning of this video.
I said this will eventually make sense. I promise. I'm sorry. I'm kind of obligated to make that joke, and if it still doesn't make sense, that's okay too. See teacher's notes for moreinformation about promises. Let's switch gears and take a look at the Python version of the helper library right after a short break. I know I need one. See you soon. (relaxing electronic music) We just took a look at Twilio's JavaScript helper library and now let's take a look at the Python helper library. Now, if you don't have Python installed, pause and refer to the teacher's notes for instructions.
In my terminal, from my home directory, I will create a new Python directory. So mkdir Python, switch to that, and while we're here, let's check and make sure we have the right version of Python. So I'm running Python 3.7.3. As long as these first three are a three and not a two, we're good to go. Python uses the concept of virtual environments. These allow you to install local packages for this application. So let's do it just to be safe. So that's done with the -m script, and then venv, for the virtual environment, and I usually call it .venv.
That will create a directory called .venv which is right there, and here we go, and what happens is I'm on a Mac now, so this might look a little different on Windows. If you use .venv, there is a directory called bin enable and I will look for that file. I think it's a .bat file on Windows. Check the notes and you'll see now that I'm activated. So I have this .venv here. I'm going to go ahead and open up my editor. So I'll do the code document and here we are. There you can see my .venv directory and I will add
Alright, I want to install the Twilio Helper Library. So I'll do Control+Tab and you'll see that my editor went ahead and ran that argument for me. So I'm already enabled here, which is good, because I want to install a package here using PIP, which stands for the sharp recursive acronym for PIP package installations. That's installing PIP and, again, Twilio. Great, it's now installed and we can start using it. So I'll come up here and we'll say from Twilio.REST import Client, and we'll create a new client, and again, it can be instantiated using, so here it gives us this good information that's available about API.
So we'll put, I'll put it here again, this is the SID of our account and, wow, it really wants to show us the SID of that account and the authentication token. So let's understand it. Again, the account SID and the authentication token. Let's put them on some of the new lines on their own. Again, it is very bad practice to leave the keys like this. We'll fix it in a moment. Now let's print the call log real quick just to show the similarities and differences between the libraries. So the Python version is synchronous, right? So we can say, then we can just iterate through those lists and messages.
So we can say for the message in client.messages.list and we will say print the message.body. Alright, let's see what that looks like. So we'll do Python and I didn't save it. That's an important part, Python, and there we go. Sent by the postman, Ahoy from the terminal. Great. So let's go ahead and discuss it for now, because we're going to do something else. So those are commented out and let's write some code to send a new one. So we'll say message is equal to client.messages.create, and here we'll pass our variables.
So we'll send it to me or in this case to you, (503)461-5537. It's my number and from, now you'll notice that from is a keyword in Python, right? So you see like from Twilio? So the nice thing is that the Python library did it from the underscore here. Help for reserved words. So my number, my Twilio number, what was that? Here it is. That's my Twilio number. Great, let's make a body and we'll say body, hello from Python. Yeah, let's go ahead and print things out. So Python has a little thing called F strings that will allow you to print variables that are in scope.
So we'll say let's create a new message and show the SID of the message to make sure we received it, and we can just do msg.sid. Hey, start with an F and use the whiskers around this for message.sid. Very similar to those string literals and JavaScript. Let's go ahead and create this one. So we'll run Python Explore, and this should send a message, and it did, and again, I want you to see that we're abstracting the fact that we're posting to the messages subresource in my account. It's happening magically, because we've signed up this customer very well, right?
The other thing this abstraction gives us is that we have instance variables that represent our resources. Now, it may not have been clear here when I walked over these objects, but they are real objects. It's not just data. They actually have methods and I can call the delete method on this message and it will be deleted. Actually, that's not a bad idea. We've been doing a lot of exploratory test messaging. Let's delete them, okay? So what I'm going to do is I'm going to come up here, uncomment this code and comment out our create message code, and convert it to an F string here.
So we'll say delete the message body. Here we are. Let's say message.delete. Cool. Now before we run this, I want you to make sure you understand that we will delete all messages from your account if you have been using a real account and have things you want to save. I strongly recommend against it. running this. Okay, you've been warned. So, here we go. I'll update this. Here we go. So we just deleted all our messages. So if we come and try to run it again, you will see that there are no messages to repeat. We have done it, clean slate.
It is as if nothing never existed. Very good, right? That helper library was able to abstract the HTTP delete call and use the information it had available in its object to make the call. Awesome. See how the helper libraries are similar but match the development workflow and style of each language? This is one of the key benefits of auxiliary libraries in general. They abstract the way the HTTP client connection from the standard REST API model. They also behave how you expect them to behave. It feels natural. The way we were able to remove from the resource itself helps unlock another element of the REST API restrictions scavenger hunt, and that is uniform design.
Now, this restriction has four subsections, one of which is the one we just discussed. Manipulating Resources through Representations, Because enough information was included, it was clear how to modify and delete this resource. Another subsection here is identifying resources in requests. Those are the URLs that are included, because the URIs are included, we know that we can obtain and manipulate specific resources. The uniform use of HTTP verbs is quite powerful. We just wrote some scripts that use helper libraries. These libraries are very useful for automation or batch scripting based tasks, making a lot of calls at once.
When we talk about this, we should cover another common tool for talking to external APIs, and that is the C-L-I, or command line interface. There I am again. Command line interfaces can be used to make API calls from an executable on your machine. More and more of these are appearing for all kinds of tools that require authentication and perform a lot of different services. This concept is popular among cloud providers, where you need to configure something quickly from the command line. See the notes for more information. Another common place you'll use helper libraries is within the applications you're building.
Let's move on to the final unit of this course and implement an external API into existing web applications. You have this. By now, I hope you're starting to see that external APIs allow you to add some pretty cool features to your apps. Do you want to send a Slack message when someone completes comments on your website? There is an API for that. Do you want to change the color of the lights in your house when your favorite sports team scores? There is an API for your equipment and for your lights if you want it. Do you want to text yourself 10 minutes before your bus arrives?
The APIs are there too. Heck, do you want to make a Furby dance? It has an API. They are everywhere and they give you a lot of power. We've seen how to use them from the command line and we've seen them used in scripts, but now let's take a look at how to incorporate them into a web application. I went ahead and built the beginnings of the web app so we can play. Now, one thing I know I don't do enough is compliment my friends, family, and even co-workers. Sometimes the web can be very negative. So I was thinking, what if we made a web application that did the opposite of that?
Introducing Complementator. So the way it works is that you fill out a web form for the person you are congratulating along with their mobile phone number. You say why they're great and they get a text telling them how great they are and encouragement to do the same, and of course they will, and when they come, they'll see the messages everyone's sent. Otherwise, they will be pleasantly surprised. I'm pretty sure we have a viral hit here. So if there were any venture capitalists watching, that's my phone number. Now, if creating and deploying a website seems like too much for your current skills, fear not, I've created a couple of code repositories that we'll use.
We'll be using a fun and accessible tool called Glitch to host our websites. The website basically works without our API that we are going to add. If you haven't used Glitch before, it's a collaborative community built around learning. You take existing projects and remix them. It has an online editor. So I want you to go to and create a user if you haven't already. Once everything is ready, let's start adding our API to the application. First, let's take a look at the Python-based web application. We will use a web framework called Flask. Flask provides an API that allows you to extend the framework to build your application.
This example application will perform server-side rendering. This means that pages will only be created on the server side. Any changes or navigation will require a full page reload. In the notes, I included a link to the repository where I have our starter code. So go ahead and copy it. Now I'll open and choose New Project. From here I will choose Clone from Git Repo. Here, I'm going to paste what I took out and I'll do, this is the one from Flask, so I make sure it's the one that says Flask. I'm going to click OK.
I've had a couple of problems with this. Sometimes this will just sit here and say loading project. If so, try the same thing a couple of times. Let's see what happens here. More or less time is running out a little. I guess it's safe to say that Glitch is Glitching. That is not fair. There must be some kind of error happening right now. I'm experiencing it. I want to record this in case you run into it so I can do it a couple of times if that happens. I want to point out that it's pretty amazing what Glitch is doing.
It's stopping us. You are sending us a completely new environment on a web server that can run, and I actually have one that is working. I did the same thing when I made a new project and you'll notice I'm not even logged in so it's okay. They don't even let you log in and create this stuff. It's good, awesome. Here we are. Down here in tools there's something called logs that you can open and it'll show you what happened. However, this is what happened. You've set up our web server here and you'll see that the server is actually running, and if you come here, you can click Show and the sunglasses here.
Your future is so bright you have to wear sunglasses. Then you can click View in new window and you will see the app is up and running, which is awesome, right? And this URL here is all yours, you can use it to do whatever. So the app itself is pretty simple. It's just a page with a form, and this section here provides messages when they finally arrive, but at the moment we don't have any, because we just deleted them all, right? But at the moment, we don't have any way to send text messages. We don't have the Twilio Helper Library installed in this app yet.
So let's come back here. These are the files that are available here. You can see here is and there are some configurations you can do here. You can go in here, you can change the name of this to be whatever you want. So I'll call this Complementer and we'll tell him to congratulate his friends. Great, and another good thing you can do is change the theme. I'll put it in dark theme. I don't know when you're seeing this, but it should be fine, both in light and dark. There you go. You can also delete this if it's not something you want, if you ended up creating something.
Very cool. Awesome. So this, this is our program. Flask works by creating an object called an application. So you name it Flask and it creates something called an application, and then what you can do is put different paths in here. So, for example, when we goShe just sent me a heart emoji. I hope now you can show your app to the person who supports you. It's really nice to have that support while you're learning and building things. If you don't have someone like that. My mom supports me a lot. If you just want to text her, I bet she'll respond with some words of encouragement.
No, of course this app won't go viral in this testing environment, but it is a great prototype of the concept. Most of the time, APS will give you a chance to put together your prototype before they start charging you, but being aware of the limits will help you plan your efforts. Remember to read the limits and error messages carefully. Most APIs will guide you on how to deal with limitations. Now let's start with a JavaScript-based Complimenter implementation. Now we will implement the same Complimenter application, this time using JavaScript. I have a mostly full-stack JavaScript application built and ready for us to modify.
By full-stack JavaScript, I mean that the server is written in JavaScript and there is front-end code that is also written in JavaScript. On the server side, the application uses Node.js and the express web framework. In the front end I have used the client side frame view. The version of Python we saw before was all server-side. There are a few things to consider when implementing a client-side application when using an API. So let's explore these as we get this JavaScript prototype up and running. In the notes, I provided a link to the repository that you can use to create the new Glitch project.
Go ahead and copy and paste it. I'll click Clone from GET repository and then paste the repository. Alright, then we'll do the Node version. So this is Node, and again, if Glitch takes a little while to work, that's okay. It might show up eventually, or it might fail, and if it fails like that, like sometimes you might just say the assets folder, just go ahead and do it again, and eventually it will work for you. Awesome, here's mine working. The JavaScript version of this project is implemented as a very simple single page application, or SPA, and what that means is that once the page is rendered, the client will be responsible for rendering parts of the page.
We will not rely on a full page reload from the server to load new pages for us. Let's take a look at app.JS, the server side of our application. Then we will see app.JS. So let's look at this first .env here. This will load our environment variables, which we'll look at here in a second. Then you use express, which is a web framework, and you'll notice that it exposes static files in a public directory. This is a single page application and is rendered in publicindex.HTML. Let's take a look there, Publicindex.HTML. So this is the view dependency.
If you haven't seen the view before, don't worry. This is a pretty simple way to use it. So what View does is it uses these V scripts, right? So it's these V script attributes, and those are view details. This basically means that if the compliments have a length greater than zero, we'll look at how the compliments are defined here in a moment, and as you can see, if it exists, it will loop through each of the compliments and then delete them. So here we'll write them using that double mustache syntax. So it will write the compliment that is in this loop.
Okay, so that compliments variable is initialized in our application. Move to down. I have put the entire application in a single file here. So we don't have to worry about packaging or anything. So the way you create a new view application is by saying new view, and you can see here that there is this data attribute and as you will see, the plugins are initialized as an empty array. You can add instance methods to your application by adding a methods object in the view constructor. So here we have a method called update praise. You may not have seen this before, but if you've had a hard time keeping track of promise-based code in the past, this feature is what you've been waiting for.
You will see here that the async keyword is before the function name. That's why it says congratulations on asynchronous update. Once a function is tagged as asynchronous, you can now make functions that return promises behave synchronously. Which means they don't move on to the next line until it is complete. So this line here does a search, right? So fetch returns a promise, but here's an oh wait keyword right before it, and this code will wait for the fetch call to complete and then assign the future value of whatever that is in the response. The same thing here with the response that JSON returns a promise, and this will wait until it is done.
One thing to note is that this async function causes the compliments update to now return a promise. That is, its return value will have a method that returns this value. Now, if that doesn't make sense yet, wait until it does. Try it and let everything come in asynchronously. A dad joke, double whammy. Sorry, I'm forced to make all these jokes. However, in reality, most developers I spoke to find this async await easier to use than code promises that are actually synchronous in nature. Alright, so what is this code doing? So you are making a GET request.
The default retrieval method is GET to a URL of /API/Compliments. That's in our server-side code. Let's go back to app.js and you define routes with express using this app.GET. Whatever the HTTP method name is. So app.GET/API/compliments, that's what we saw. So when that happens, this function here will run and we'll pass the request and the response, and this is the first one to do it: We want to get the message log. So before we do that, we'd better install the Twilio Helper Library using NPM. So I'll click on Tools, then I'll click on these logs, and then I'll click on Console.
Now I'll run the NPM setup, install Twilio, and do --save. What that will do is update a file called Package.JSON after you install it, and this is very similar to what we saw in the Python library, we did the freeze, this --save will update that file so that the Twilio dependency is there . . We'll let this play out. Great, now when you make a change from this side, we always have to say update so we can update the project and see the changes we made, and if we look here in the .JSON package, you can see that there is a dependency on Twilio.
Great, now that we have everything installed, let's go ahead and update the .env file. So that's this key. See this little key.env here? This will allow us to put our information here. So I'm going to go ahead and grab the SID of my account. You should do the same with yours and take my authentication token and last but not least my phone number. Alright, now we can use that in our code. Let's go right above this port. Just below this port here. We'll create a new Twilio client and demand it, in fact, it probably looks better a little higher up.
Let's move that. Let's do it right. This is all out of alphabetical order, right? Let's do this right here. There we go, and then we can create an instance that will look better down here. So I'm going to say constant client is equal to new Twilio client, and again, it's going to be pulled from the Twilio underscore environment variables, and just to show you how that's done here. Then we will say constant the TWILIO_PHONE_NUMBER. If you ever wanted to get something else out of the environment, you use process.env.thething. So the thing was called Twilio, I think it's called a phone number.
Let's double check TWILIO_PHONE_NUMBER and env.TWILIO_PHONE_NUMBER. Yes, great, incredible. So let's get that message log. So what I'm going to do is replace this. Then we get the compliment. Then we get messages sent. So this to get a list of messages sent from a specific number, obviously the Twilio number there. So what I'm going to do is replace this array with my code, and do you really want to give this a spin? Well, one thing to note is that the function is marked as asynchronous. So you can, and probably should, use the await keyword, right?
So this is an asynchronous function. So make sure you use the wait keyword. Are you ready? Simply make the call to the Messages API to get a list of messages that were sent to a specific number. As the pending task says. Don't worry if you don't have it memorized, I put a link to the documents in the notes. Go ahead, pause and try it. When I get back on track, I'll show you how I did it. Ready? How would you do it? So what I did was client.messages.list, and in the JavaScript client helper library, you pass in an object with the parameters.
So we say there's no keyword here, and we'll say TWILIO_PHONE_NUMBER, and like I said, we should make this a wait, because we're going to wait for that to happen, and boom, just like that to do it, well, why don't we we changed? Why don't we take a look? Come on. I'm going to change this to Complementer from a mentor who isn't very friendly with Complimenter.js. Congratulations, I'll close that and let's move on and show when we should see the messages arrive. Oh, we shouldn't see the message arrive yet, should we? Because nothing is happening.
We are passing on these praises. OK let's see. Let's see if we can do this next to do it. Gather only the body of those messages to send to the client. Well, sure, because we don't want to send the entire message object to the client. So what we want to do is make the API called plugins, right? And we have a variety of text messages. But the most important thing is that if I were to send this message, each one of those messages contains a lot of information that I don't think we want to share with everyone.
That message has the phone number of the people who sent the message. I should never send information that I want to keep secure to the client. So we really just want the body. So let's see, I have an array and I want a new array of just message bodies. Now, to me, this sounds like a great use of the function. So the messages sent are an array. We will say messages, and the map function, map takes a function that will receive each value in the array. So it's going to be a message and it requires a function, and if it's on a line, we can skip the return keyword and just put in what we'd like to see.
So in this compliments array, we want to see the message.body array, right? So what this says is that for each of these messages here, just return the body of the message and put it in compliments. It makes sense, and then it will send the JSON representation of that to our display client. Should we see if it works? All right, we'll save this and now, here we go. It's already working. Then we'll see. There's a new one from my mom, and she says, mom says, Craig is so proud of you, honey. Oops, it's cute, it's sweet.
She responded to me and that's what I love about someone using your apps. Looks like I still need to work on the UI to make it clearer what's going on, because my mom wrote "proud of you, darling" in the compliment, and that doesn't make much sense, but I feel good, and again this. you are using the number, this was not sent from this app. You can see that it was sent from the Python application, right? This is Complimenter.js, but it uses a different data source, and you know what? While we're here, why don't we see how easy it is to see what data was sent from the server?
So I'll right click and choose Inspect. I'll click on this Network tab here, refresh the page, and you'll see that it makes that request. So if I click on Congratulations here, you can see here's the message. Here is that array that was sent, right? You can imagine that if we sent all those messages, it would be very easy to obtain that data. Again, these are the developer toolbars. If you say View, Developer, Developer Tools, you'll be able to see this. I'm going to take a short break and then I'll come back and finish what's left to do, creating a new compliment. (relaxing electronic music) We just finished listing all the compliments, and now it's time to address how they are added on the JavaScript side.
So let's keep the front code and see what happens. That's in publicindex.HTML. So here is that form. Alright, we have this, it's a form that will be published. You go to /add plugin and you have these V Dash models. So here's the V Dash, model two, Videsh sender model, and this is how the view binds the data. So anything in that field will be tied to that variable, and if we go down to the button here, we'll see that the normal click won't prevent that, right? That prevents it from being sent and calls this send compliment method, which is defined here in the method section, which is this send compliment.
Well then go ahead and take the thingsof the form to get them all. It also turns out that they are the same, they are in something called data, then you use fetch and you use it synchronously, right? So you have to wait, it will wait for the search to be done and it passes it as JSON, and we were saying it's JSON, and we're passing JSON, and we're making a post request, and we go. Go ahead, and we'll take a look at app.js, and we'll see here that we're using these body parts here, so any request that comes in will be parsed automatically, and the way it looks is, So here's this post, right?
TRUE? So we fail, we fix this problem and we have to get rid of these two things to do. I forgot to delete them. Those are yet to be done. All right, it comes here and it's posted to the API, again, an asynchronous method. Then it will also exit the request body, right? So, and because the body was analyzed, it automatically inflates here. So, take out the body of the two, it will take them off the field and request the body sender, or Costa's biosphere, a big compliment, and you're using Bactec to auto-complete them. Here we are.
This is what we must do. Why don't we create that message synchronously? Well, do you want to try this? Go ahead and pause. I put links in the notes, I'll wait for you to get back to me and then show me how you did it. How did it go? This is how I did it. That's why we want it to be synchronous. So I'm going to go ahead and use await, and I don't really need anything from creating a message, so I'm not going to assign a return value and I'm going to use the fact that the parameters are the same. .
So I'll say client.plant.messages.create, and in JavaScript you can do this. If you have a variable called two, it will simply be set to 2:2 from the addition, right? Basically, this is because there is a variable called two, and it knows how to create a new one called two in this array here. Alright, let's try it. So I'm going to go ahead and click Show Here and send another one to my mom. For mom, no, my name is not mom. Well, my name is Craig and I'm going to congratulate mom. The compliment of her is a really patient tester.
Mom is a very patient evaluator. So, here we go. Yes, there it is. So see right away that it's back and you'll see that the forms have been cleared. So let's see how he did it. So back in index.HTML we have this, we posted it, it got the data, it waited for the result, then it wrote the result and we saw this information coming down. So if we wanted to, we could do View, Developer, Developer Tools and we should see in the console. Here is the object that was returned. So it was a fake success.
Now, we forgot to update that, right? I'll have to look. I thought we looked at that. Now, if you're going to say, yeah, that was a successful trip there. Good job. I'm glad I caught it. Speaking of catching things, what if something goes wrong? Just like before when we needed to catch the error using catch method on promises, we need to do something similar in this asynchronous wait land. So we need to use a standard try catch block. Now, if you haven't seen it before, it's pretty simple. What you do is you say try, and if any errors occur, what will happen is you'll call this catch block, and it's a good way to handle errors.
So let's catch that error. So the error object has a state and you can send it to the client by saying response.status, and we can do error.status. We'll just pass that state directly and this can be changed. Then we will send JSON, maybe as it happened. So this time we will say success is fake for real and also send, why don't we send the message? We will send that error error.message. Here we go, and you know what? We can use prettier here as well. So we'll click on this format, this file. Let's make this more beautiful.
Oh, great. Well, let's try it, and if there's an error, we'll send this back, and if not, we'll go ahead and send the real success. So we have to break it somehow. How should we do that? Let's say instead of since, let's make this 42, the meaning of life and all. Obviously, that is not a valid TWILIO_PHONE_NUMBER. So let's go ahead and bring in Subo Complimenter, and I'm going to oh, it's updated. I was going to update it and it did it for me. Then we'll send another message to my mom. My name is Craig for my mom and the compliment is good for catching mistakes.
Okay, I'll click Send a Compliment. Let's see what happens. Oh look, here we have the error. It is a 400 that returned and the one for phone number 42 is not valid. CMS capacity, incoming number or short coverage of your account is a better version. Cool, right? And let's make sure we don't leave that in that state. So we'll undo that and save it, because I want my mom to give me another compliment. Again, we're ready to go. Awesome job. You have now used an external API in two completely different web frameworks and even paradigms. You should pay yourself a compliment.
You are achieving great things. What a way to move forward. Another thing I'd like to take a moment to point out is that the server code that we wrote, you may have noticed was prefixed with /API server code that interacted with a client. Now here is my question for you. Do you think the API code we write together should be considered RESTful? Why don't we take a look at our worn-out scavenger hunt card? It is definitely a Client-Server architecture. Our client turns out to be, in this case, a viewer application running in the browser, and our server is a Node.js server, but any client could connect and use it.
He's definitely stateless, right? We do not require any prior knowledge about the client. Well, at the moment we don't provide any caching information, so we could do that, right? We could easily pay attention to the headlines that come in and respond appropriately. It would require us to write additional code and think about some edge cases, but we could do it. Let's put this in the maybe column. Yes, sure, true. In fact, it's already a bit layered. Our API calls another API, but our client doesn't need to know about it. We could also add additional functionality and the contract would not change.
We haven't even talked about this yet and it's the only optional requirement. This basically means that your API returns some code that can be executed, like maybe it returns an embeddable widget or some actual JavaScript code. This doesn't make sense in our application and that's okay. I'm going to leave this at no, so we're looking good so far, but here's the cool thing. So remember this has four subsections, row of furrows. We currently only represent all plugins as strings and there is no way to identify them. So we didn't meet this subrequirement and therefore this is a no, but let's move on to the rest.
Pun intended, sorry. We definitely do not allow any kind of manipulation of praise. So this is another failure. We haven't gone over this yet, but by using headers we can tell that this is JSON. The message sent has a type, and it is clear that it must be decoded into JSON to be used and last but not least, Hateos or Hate OS is a part of the RESTful constraint that is often forgotten and very difficult to understand. say. The idea here is that links are provided to show what else can be done with this and where related resources can be found.
Provides URIs or links. We saw this on both Spotify and Twilio. However, ours does not need to provide links to other resources. So we don't have a RESTful API, and that's okay. It works as is. It looks like we could get there pretty quickly if we wanted to. One thing I want you to get out of that exercise is that you now have the ability to identify whether an API is RESTful or not, and I hope that felt pretty good. We've already completed that treasure hunt. We revealed all the limitations and I hope most of them are pretty clear.
Please don't feel like you need to memorize them. You can find these same restrictions scattered all over the Internet as a reward for finishing the restrictions scavenger hunt. I've included links to my favorite REST API constraints documentation for you to check out. I have also included links to popular REST API frameworks that will help you design RESTful APIs. Be sure to review the notes. You did it. You've just completed a quick introduction to APIs and I hope you see how much power they can add to your programming journey by looking at interfaces in general. I hope you become more comfortable with the idea of ​​not fully understanding exactly how something works, but still leaning on that abstraction to create your tools and applications.
We do this all the time with physical object interfaces and APIs or application programming interfaces are not that different. I hope you enjoyed taking this course. I know I had a lot of fun doing it. If you think someone you know could benefit from this course, please share it with them. I would love to hear your feelings, your thoughts and your dreams. So I put together something using some APIs to capture their comments. If you have time, I'd love for you to take a quick text-based survey. Text your comments to 1-503-461-5537. Actually, you know what?
If you want, you can also call me and leave me a message too. I also used an API for that. Please, please keep me posted on your journey and I really can't wait to see what you build. Thanks for hanging out. (relaxing electronic music)

If you have any copyright issue, please Contact