What is an API?
What is an API? Well, API stands for Application Programming Interface, and really this is a set of rules that allow different software systems to communicate with each other. An API typically lives on some type of server and will manipulate some kind of database. It can handle different requests. So if I'm a user utilizing the API, I send a request to it. My request may contain some different data, then the API is going to process this request and return to me a response. That response will typically contain data that I was requesting from the API.
Typically, your API will manipulate some type of database and allow different access to the database values depending on the set of rules that you set up. In this video, I'll show you how to set up a simple API using Python and Flask in under 10 minutes. So that said, let's go ahead and get started.
After a quick word from our sponsor. If you're interested in rapidly creating APIs, then today's sponsor Dream Factory has you covered. With Dream Factory, you can create fully featured APIs in seconds by simply connecting to a data source. Let me show you.
Begin by starting your Dream Factory instance, logging in, and then connecting to a data source. For this demo I'll use MongoDB. I'll fill in my connection details, press save, and in seconds Dream Factory has created a fully customizable and fully documented REST API that I can now use to access my data. Look, I can query my reviews collection and view a result in a matter of seconds. Now that my API is created, I can go ahead and add authentication by making a new rule, connecting that rule to a new application, and generating a unique API token. Now that I have this token, I can access my API securely from anywhere. Look at me doing it here right in Postman.
Now best of all, Dream Factory APIs are fully customizable, can run anywhere, and connect to your existing authentication systems like OAuth. Spend less time writing backends and more time developing beautiful applications by clicking the link in the description and getting started with Dream Factory today. Thanks again to Dream Factory for sponsoring this video.
Setting Up Your First Flask Route
Alright, so let's begin with our project setup. For this video, we're going to use Flask. This is a micro web framework for Python that's very popular for doing web development and for creating APIs. To set up Flask, we first need to open some kind of terminal window. In this case, I'm in command prompt. If you're on Mac or Linux, open your terminal and we're going to type the following command, which is pip install and then flask. Now, this should install the flask framework for you. If you're on Mac or Linux, you may want to try the pip3 command if pip was not working for you. And if neither of those commands work, I'll leave two videos on the screen that will show you how to fix that pip command.
Now that we have Flask installed, we're just going to open a Python file, which I already have here in some kind of directory, and we're going to create a basic Flask application. Flask will be the server that's running our API. We're going to begin by importing our dependencies. We'll say from flask import and then we're going to import Flask with a capital, request, and then the function jsonify, which we're going to use to create a JSON response. Now we need to create our Flask application. So we're going to say app is equal to Flask and then underscore underscore name underscore underscore like that. And then we're going to run our Flask application by saying if __name__ == "__main__": app.run(debug=True). This will run our Flask server.
Now that our Flask server is set up and we have the basic initialization, what we need to do is create something known as a route. Now, a route is essentially an endpoint. This is kind of a location on our API that we can go to to get some kind of data. We have different kinds of routes, which I'll talk about in a second, but for now let's create a simple one and test this out so you can see how it works. So to create a route we're going to define a Python function. We're going to say def, in this case we'll go with something like home. Inside of our function, we'll just return some data that we want the user to have access to when they reach this route. So we'll say return and in this case go with something like home.
Now, to make this accessible, what we need to do is add a decorator. We're going to use an at symbol and say @app, which is the name of our Flask application here, so use the same variable name, .route. Then we're going to put the path that we want to access. In this case, we're just going to do /, which will be the default route. Now, the route is really what comes after the slash in your URL address bar, so that's what we're setting up here. Okay, let's save our code and let's go ahead and run this. To run this, we're going to type python and then main.py, which is the name of my Python file. If you're on Mac or Linux, you're going to use python3. Okay, so let's run that. You can see that it's now created a development server for us, and I can open this URL by just right-clicking on it here in Visual Studio code. When I do that, you can see that I get "home" appearing on my screen. There you go, you just created your first route inside of Flask.
Understanding HTTP Methods
So now that we've created this demo route, let's have a look at some other routes that we can create with different HTTP methods. Now, whenever we're writing an API, we're working with something known as HTTP, which is essentially the way we communicate data over the internet. Now, when we create different API routes, we can mark them with different methods. Now, the methods we can use are GET, POST, PUT, and DELETE. We have access to a bunch of other ones as well, but these are the most common ones.
Now, GET is used when we want to retrieve some value from the server. POST is used when we want to create something new. PUT is used when we want to alter or modify some existing data. And DELETE is used when we want to remove or delete data from a database or from whatever resource it is that we're accessing.
Creating a GET Route with Parameters
So let's create a more complicated GET route here and see how that works. So we're going to say @app.route. For this, we're going to say /get-user and then I'm going to implement something known as a path parameter. Now a path parameter is a dynamic value that you can pass in the path of a URL that we'll be able to access inside of our route. So in this case, I'm going to say <user_id>. Then I'm going to make my function get_user and I'm going to accept a variable inside of my function parameters here that's the same as the path parameter I put here. Now when we do this, this essentially means that I can do something like get-user/ and then any value I want and this value will be the ID of the user that we're attempting to retrieve, right? So if I have something like 6226, then that's indicating that I want to retrieve the user with the ID of 6226. Okay, that's a path parameter.
So how do we access the path parameter? Well, we can just access it directly from here. So what I'm going to do is essentially mock some data that we want to return to our user. So I can paste this in: user_data is equal to the following. And now I want to talk to you about something known as a query parameter. Now, whenever we are accessing a route, we have the ability to pass something known as a query parameter, which is essentially an extra value that is included after the main path. So if I have my path get-user/123, if I put a question mark here, now I can pass different query parameters, so something like extra=hello world. Okay, this is an additional variable that I can pass along to my route. So how do I access that from Flask? Well, I can do the following. I can say extra = request.args.get('extra'). request is the variable I imported up here, .args which stores all of my query parameters in a dictionary, and then I can use .get and try to access a value like extra.
Okay, now that I have extra, I can check if this exists. So I can say something like if extra:, then user_data['extra'] = extra. Then I can return my data. So I can say return jsonify and then this will be my user_data. I'll pass the response code of 200.
So whenever we are returning data from an API, we're going to use JSON. Now, JSON stands for JavaScript Object Notation, which is essentially a collection of key-value pairs very similar to a Python dictionary. So in Flask, we create a dictionary, and then we jsonify that dictionary, and that's what we can return to the user. This allows Flask to actually parse this value and return it as JSON data. The next value that we pass here is the status code. 200 is the default status code of success. You can pass other HTTP status codes here as well. I won't go through all of them. So now that we have this GET route, let's make sure our server is running. So let me just bring up my terminal here and run my server and now we can actually test our GET route from the browser. By default, when you actually type in a URL here in your browser, you're going to be sending a GET request. So notice here that I have the URL of get-user/123?extra=hello, and then it returns to me the JSON data of this, which has my user ID and then what I passed here inside of the query parameter.
Creating a POST Route to Receive Data
Now that we've had a look at how to make a GET route, let's have a look at making a POST route. So to create a POST request, we'll do a very similar thing to what we did before. We'll have an @app.route. We'll go here and we'll say slash and then this can be something like /create-user. However, this time, since we're not using the default GET request, we have to actually specify the accepted method for this route. So in this case, I'm going to put inside of an array here POST. Now, this means that I can accept a POST request. If I wanted to accept both a POST request and a GET request, then I would put both of them inside of here. For now, all I want to accept is POST.
Then I'll define my function create_user. And if I wanted to check inside of this function what the method was that was being used, I could do the following. I could say if request.method == 'POST'. I would only do this if I had multiple methods, but I just wanted to show you you can use request.method, which is from this variable right here and it tells you if you're using POST, GET, etc.
Regardless, we know it's going to be POST. What we want to do here is actually receive some data from the request that's in JSON format. So the user is going to submit us some JSON, which is kind of the user they want to create. So how do we get that? Well, I'm going to say data = request.get_json(). This is going to give me all the JSON data that was passed in the body of the request. I'm going to show you how we look at this in a second and what I can do is simply return this back to the user to indicate that this was created successfully. So I can say return and then I need to jsonify(data) and then I can return the status request of 201. And now we have successfully implemented a POST request where we are receiving some JSON data from the user. Obviously, I'd probably do something more here like add this to a database, but this is just a simple demo.
Testing Your API with Postman
Okay, so now we've created this POST request, however, I can't demo the POST request for you in the browser. So now we're going to quickly talk about how we can test our APIs. Now there's a variety of different ways we can test our APIs, but I'm going to recommend we use a tool called Postman. So please download this from the link in the description, and then open up that software and let's look at how we can call this API.
Alright, so my Python server is running, so I'm going to copy the URL that it's running on right here, which is localhost Port 5000. I'm going to open up my Postman software. I'm going to click plus here to create a new request. I'm going to paste this in, change the URL to create-user, change the method here to be POST, and then I'm going to go to where it says body, because this is where I'm going to include my JSON data. I'm going to change this to say raw data. I'm going to go here to text and change this to not JavaScript but JSON. I'm going to pass a JSON object, so the way I do that is have a set of curly braces just like my Python dictionary. I'm then going to go and make a key, my key will be username and I'll have this associated with the value, sorry, Tim. Now if I hit send, you can see that we get this exact same data back with the status code of 201 and that means that this is working successfully. So this is a great tool that you can use to test out your APIs as you continue to do more development.
Conclusion & Next Steps
So with that said, that will wrap up this video, but I will encourage you to learn more by checking out this video here, which is on FastAPI, or this video here, which is creating a more advanced API in Flask that uses authentication. Really, the next step here is to authenticate your APIs and connect them to a database. Obviously I didn't have time here. With that said, I hope you enjoyed and I look forward to seeing you in another one.