Alfie Mellor

Alfie Mellor

1559709440

Working with APIs using Flask, Flask-RESTPlus and Swagger UI

The article discusses about how to use Flask and Flask-RESTPlus to create APIs and then use them to send and retrieve information.

While working on Machine Learning projects, I decided that I would like to develop complete applications. This would require developing APIs, so that we can post values and get responses of predictions. This is where Flask and Flask-RESTPlus come into the picture.

Flask enables exposure of Python functions as APIs. Flask-RESTPlus is an extension to Flask which improves upon its capabilities. It allows us to not only define REST APIs but also brings in Swagger UI for all the APIs.

In this article, I’ll explain how I developed a Flask application with several APIs and dummy data. The project is available as a GitHub Repository.

Installation

I began the process by creating a virtual environment using pipenv. You can read more about it in my article on comparison of virtual environments. I installed Flask and Flask-RESTPlus.

pipenv install flask
pipenv install flask-restplus

However, if you do not wish to work inside a pipenv environment, you can simply use the following commands.

pip install flask
pip install flask-restplus

Basics

Import

I began by importing Flask from flask. From flask_restplus, I imported Api to define the app and Resource which is received as a parameter in the various classes defined in the project.

from flask import Flask
from flask_restplus import Api, Resource

Define App

I defined the application as a flask application using the method Flask() which sets the name using __name__. Next, I’ll used Api to initialise the application.

flask_app = Flask(__name__)
app = Api(app = flask_app)

name_space = app.namespace('main', description='Main APIs')

I defined a namespace here. The concept is very simple. Whenever APIs are defined under a given namespace, they appear under a given heading in Swagger (we’ll explore Swagger later in this article). In namespace, the first variable defines the path and second defines the description for that space.

In the example above, the url for the namespace is [http://127.0.0.1:5000/main](http://127.0.0.1:5000/main "http://127.0.0.1:5000/main") and has the description as Main APIs in Swagger.

Define APIs

Lastly, I defined the endpoints. As our namespace is name_space, I’ll define the url through route as @name_space.route("/"). Next, Flask-RESTPlus requires us to define all endpoints under a given route inside a class. The methods can beget(), put(), and many others.

@name_space.route("/")
class MainClass(Resource):
	def get(self):
		return {
			"status": "Got new data"
		}
	def post(self):
		return {
			"status": "Posted new data"
}

In the example above, the APIs can be accessed at the path [http://127.0.0.1:5000/main](http://127.0.0.1:5000/main "http://127.0.0.1:5000/main"). The classname is set as MainClass with two methods, get() and post(). Whenever, I make a GET call, I get the reply with status field as Got new data and with POST call, I get the reply as Posted new data.

Run App

Now, everything is set up. The file is saved as basic.py. I run the app by the following command using pipenv.

pipenv shell
FLASK_APP=basic.py flask run

Using pip, you can use the following command.

FLASK_APP=basic.py flask run

Swagger UI

The best part of Flask-RESTPlus is that it automatically documents the APIs that we have created and they are visible in the Swagger UI. Go to [http://127.0.0.1:5000/](http://127.0.0.1:5000/ "http://127.0.0.1:5000/") and you can see all the APIs.

Both APIs are visible under the main namespace with the description Main APIs. We can try either API and check their functioning by clicking the Try it out button.

Try API

I used curl to make GET and POST requests from the terminal.

While using the curl command, first use the word curl followed by the method after the character -X. Finally, the endpoint is specified. Taking a look at our curl responses, we see that I received the correct data for both GET and POST APIs.

Taking it up a notch

There is so much more to Flask and Flask REST-Plus. Let’s explore them in even more depth and understand them better. The following code is available as [app.py]([https://github.com/kb22/Understanding-Flask-and-Flask-RESTPlus/blob/master/app.py)](https://github.com/kb22/Understanding-Flask-and-Flask-RESTPlus/blob/master/app.py) "https://github.com/kb22/Understanding-Flask-and-Flask-RESTPlus/blob/master/app.py)") in the GitHub Repository.

We can use a POST request to send data and save it. We can then use the GET request to get that data. Let’s say we have a project that manages names of individuals and stores them. We create a GET endpoint to fetch the name using id and POST endpoint to save a name against an id.

Here, I have created the path as [http://127.0.0.1:5000/names/<int:id>](http://127.0.0.1:5000/names/ "http://127.0.0.1:5000/names/<int:id>") where we will pass the id each time. To store names, I have created an object list_of_names which will be used to get and receive data.

Import more libraries

We have already imported Flask, Api, and Resource. We also import request from the flask package. This helps us get the request object and then retrieve information such as JSON data from it. We also import fields from flask_restplus package to define the type of elements such as String.

from flask import Flask, request
from flask_restplus import Api, Resource, fields

Add Application Information

We can also add extra information to our Flask app. This information is useful and is displayed in the Swagger UI.

flask_app = Flask(__name__)
app = Api(app = flask_app, 
		  version = "1.0", 
		  title = "Name Recorder", 
		  description = "Manage names of various users of the application")

name_space = app.namespace('names', description='Manage names')

We can define the version, title and the description of our application. We’ve set only one namespace namely names. The Swagger UI header would now look like the image below.

Define Models

Whenever we want to receive or send information in a particular format (JSON) we accomplish this with the help of model. We specify the name of the model. Next, we describe the information it expects and the properties of each expected value.

model = app.model('Name Model', 
		  {'name': fields.String(required = True, 
					 description="Name of the person", 
help="Name cannot be blank.")})

We define the model name as Name Model. It includes one parameter, namely name which is a required field, and define its description and help text. The API which will use this model will expect a JSON with a key as name.

list_of_names = {}

To keep track of all names, I’ll store them in list_of_names.

Define APIs

@name_space.route("/<int:id>")
class MainClass(Resource):

	@app.doc(responses={ 200: 'OK', 400: 'Invalid Argument', 500: 'Mapping Key Error' }, 
			 params={ 'id': 'Specify the Id associated with the person' })
	def get(self, id):
		try:
			name = list_of_names[id]
			return {
				"status": "Person retrieved",
				"name" : list_of_names[id]
			}
		except KeyError as e:
			name_space.abort(500, e.__doc__, status = "Could not retrieve information", statusCode = "500")
		except Exception as e:
			name_space.abort(400, e.__doc__, status = "Could not retrieve information", statusCode = "400")

	@app.doc(responses={ 200: 'OK', 400: 'Invalid Argument', 500: 'Mapping Key Error' }, 
			 params={ 'id': 'Specify the Id associated with the person' })
	@app.expect(model)		
	def post(self, id):
		try:
			list_of_names[id] = request.json['name']
			return {
				"status": "New person added",
				"name": list_of_names[id]
			}
		except KeyError as e:
			name_space.abort(500, e.__doc__, status = "Could not save information", statusCode = "500")
		except Exception as e:
name_space.abort(400, e.__doc__, status = "Could not save information", statusCode = "400")

Let’s break down the code snippet above into smaller parts to understand it better. We’ll explore the POST endpoint. The functionality of GET would be very similar.

Define route and class

@name_space.route("/<int:id>")
class MainClass(Resource):

We use the name_space namespace to define the route i.e. [http://127.0.0.1:5000/main/<int:id>](http://127.0.0.1:5000/main/ "http://127.0.0.1:5000/main/<int:id>"). It expects an Id to be sent as an integer. The name of out class is MainClass which has one parameter, Resource.

Define docs for the API

@app.doc(responses={ 200: 'OK', 400: 'Invalid Argument', 500: 'Mapping Key Error' }, 
params={ 'id': 'Specify the Id associated with the person' })

Using doc we can define the documentation for the API in Swagger. The responses key defines the various possible HTTP Status Codes. For each status code, we also define a text that describes it to the user. The params key defines the expected parameter. The API expects id in the URL and we specify a help text for the user. The Swagger UI looks like the image below.

The parameters are defined in the top part. All the expected responses with their description appear in the lower part.

Define the method

@app.expect(model)		
def post(self, id):
  try:
    list_of_names[id] = request.json['name']
    return {
      "status": "New person added",
      "name": list_of_names[id]
    }
  except KeyError as e:
    name_space.abort(500, e.__doc__, status = "Could not save information", statusCode = "500")
  except Exception as e:
name_space.abort(400, e.__doc__, status = "Could not save information", statusCode = "400")

We can now define our method. Before our method, we add the line expect(model) which defines that the API expects model. We wrap our code inside a try block and catch all errors that might occur. The request.json['name] gets us the received name and we can save it as well as send it back in the response. If the name key is missing, we get KeyError and we send Status Code 500. In other cases, we send Status Code 400.

Try the App

Let’s start the app.

FLASK_APP=app.py flask run

POST

We parse the response from the request, read the name and store it against the id in list_of_names. We also return the status and the name of the newly added person.

Error in POST Request

Say, we forgot to supply the name parameter in the data object. In this case, we’ll get an error.

On not supplying the key name, we got an error with Status Code 500 and the message Mapping key not found.

GET

We just pass the id that we want to get the name for and we get the status and the name of the person back if available.

Error in GET Request

Say, we don’t have any person against Id 2. If we try to retrieve that information, it’ll throw an error.

As that specific Id is not found, we get Status Code 500 and the message Mapping key not found.

Conclusion

In this article, we explored creation of APIs using Flask and Flask-RESTPlus. Both of these are great libraries to develop as well as document APIs in Python and interact with APIs using Swagger.

Please feel free to share your thoughts and ideas.

#python #flask #rest #api

What is GEEK

Buddha Community

Working with APIs using Flask, Flask-RESTPlus and Swagger UI
Sival Alethea

Sival Alethea

1624302000

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

What is an API? Learn all about APIs (Application Programming Interfaces) in this full tutorial for beginners. You will learn what APIs do, why APIs exist, and the many benefits of APIs. APIs are used all the time in programming and web development so it is important to understand how to use them.

You will also get hands-on experience with a few popular web APIs. As long as you know the absolute basics of coding and the web, you’ll have no problem following along.
⭐️ Unit 1 - What is an API
⌨️ Video 1 - Welcome (0:00:00)
⌨️ Video 2 - Defining Interface (0:03:57)
⌨️ Video 3 - Defining API (0:07:51)
⌨️ Video 4 - Remote APIs (0:12:55)
⌨️ Video 5 - How the web works (0:17:04)
⌨️ Video 6 - RESTful API Constraint Scavenger Hunt (0:22:00)

⭐️ Unit 2 - Exploring APIs
⌨️ Video 1 - Exploring an API online (0:27:36)
⌨️ Video 2 - Using an API from the command line (0:44:30)
⌨️ Video 3 - Using Postman to explore APIs (0:53:56)
⌨️ Video 4 - Please please Mr. Postman (1:03:33)
⌨️ Video 5 - Using Helper Libraries (JavaScript) (1:14:41)
⌨️ Video 6 - Using Helper Libraries (Python) (1:24:40)

⭐️ Unit 3 - Using APIs
⌨️ Video 1 - Introducing the project (1:34:18)
⌨️ Video 2 - Flask app (1:36:07)
⌨️ Video 3 - Dealing with API Limits (1:50:00)
⌨️ Video 4 - JavaScript Single Page Application (1:54:27)
⌨️ Video 5 - Moar JavaScript and Recap (2:07:53)
⌨️ Video 6 - Review (2:18:03)
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=GZvSYJDk-us&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=5
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#apis #apis for beginners #how to use an api #apis for beginners - how to use an api #application programming interfaces #learn all about apis

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Alfie Mellor

Alfie Mellor

1559709440

Working with APIs using Flask, Flask-RESTPlus and Swagger UI

The article discusses about how to use Flask and Flask-RESTPlus to create APIs and then use them to send and retrieve information.

While working on Machine Learning projects, I decided that I would like to develop complete applications. This would require developing APIs, so that we can post values and get responses of predictions. This is where Flask and Flask-RESTPlus come into the picture.

Flask enables exposure of Python functions as APIs. Flask-RESTPlus is an extension to Flask which improves upon its capabilities. It allows us to not only define REST APIs but also brings in Swagger UI for all the APIs.

In this article, I’ll explain how I developed a Flask application with several APIs and dummy data. The project is available as a GitHub Repository.

Installation

I began the process by creating a virtual environment using pipenv. You can read more about it in my article on comparison of virtual environments. I installed Flask and Flask-RESTPlus.

pipenv install flask
pipenv install flask-restplus

However, if you do not wish to work inside a pipenv environment, you can simply use the following commands.

pip install flask
pip install flask-restplus

Basics

Import

I began by importing Flask from flask. From flask_restplus, I imported Api to define the app and Resource which is received as a parameter in the various classes defined in the project.

from flask import Flask
from flask_restplus import Api, Resource

Define App

I defined the application as a flask application using the method Flask() which sets the name using __name__. Next, I’ll used Api to initialise the application.

flask_app = Flask(__name__)
app = Api(app = flask_app)

name_space = app.namespace('main', description='Main APIs')

I defined a namespace here. The concept is very simple. Whenever APIs are defined under a given namespace, they appear under a given heading in Swagger (we’ll explore Swagger later in this article). In namespace, the first variable defines the path and second defines the description for that space.

In the example above, the url for the namespace is [http://127.0.0.1:5000/main](http://127.0.0.1:5000/main "http://127.0.0.1:5000/main") and has the description as Main APIs in Swagger.

Define APIs

Lastly, I defined the endpoints. As our namespace is name_space, I’ll define the url through route as @name_space.route("/"). Next, Flask-RESTPlus requires us to define all endpoints under a given route inside a class. The methods can beget(), put(), and many others.

@name_space.route("/")
class MainClass(Resource):
	def get(self):
		return {
			"status": "Got new data"
		}
	def post(self):
		return {
			"status": "Posted new data"
}

In the example above, the APIs can be accessed at the path [http://127.0.0.1:5000/main](http://127.0.0.1:5000/main "http://127.0.0.1:5000/main"). The classname is set as MainClass with two methods, get() and post(). Whenever, I make a GET call, I get the reply with status field as Got new data and with POST call, I get the reply as Posted new data.

Run App

Now, everything is set up. The file is saved as basic.py. I run the app by the following command using pipenv.

pipenv shell
FLASK_APP=basic.py flask run

Using pip, you can use the following command.

FLASK_APP=basic.py flask run

Swagger UI

The best part of Flask-RESTPlus is that it automatically documents the APIs that we have created and they are visible in the Swagger UI. Go to [http://127.0.0.1:5000/](http://127.0.0.1:5000/ "http://127.0.0.1:5000/") and you can see all the APIs.

Both APIs are visible under the main namespace with the description Main APIs. We can try either API and check their functioning by clicking the Try it out button.

Try API

I used curl to make GET and POST requests from the terminal.

While using the curl command, first use the word curl followed by the method after the character -X. Finally, the endpoint is specified. Taking a look at our curl responses, we see that I received the correct data for both GET and POST APIs.

Taking it up a notch

There is so much more to Flask and Flask REST-Plus. Let’s explore them in even more depth and understand them better. The following code is available as [app.py]([https://github.com/kb22/Understanding-Flask-and-Flask-RESTPlus/blob/master/app.py)](https://github.com/kb22/Understanding-Flask-and-Flask-RESTPlus/blob/master/app.py) "https://github.com/kb22/Understanding-Flask-and-Flask-RESTPlus/blob/master/app.py)") in the GitHub Repository.

We can use a POST request to send data and save it. We can then use the GET request to get that data. Let’s say we have a project that manages names of individuals and stores them. We create a GET endpoint to fetch the name using id and POST endpoint to save a name against an id.

Here, I have created the path as [http://127.0.0.1:5000/names/<int:id>](http://127.0.0.1:5000/names/ "http://127.0.0.1:5000/names/<int:id>") where we will pass the id each time. To store names, I have created an object list_of_names which will be used to get and receive data.

Import more libraries

We have already imported Flask, Api, and Resource. We also import request from the flask package. This helps us get the request object and then retrieve information such as JSON data from it. We also import fields from flask_restplus package to define the type of elements such as String.

from flask import Flask, request
from flask_restplus import Api, Resource, fields

Add Application Information

We can also add extra information to our Flask app. This information is useful and is displayed in the Swagger UI.

flask_app = Flask(__name__)
app = Api(app = flask_app, 
		  version = "1.0", 
		  title = "Name Recorder", 
		  description = "Manage names of various users of the application")

name_space = app.namespace('names', description='Manage names')

We can define the version, title and the description of our application. We’ve set only one namespace namely names. The Swagger UI header would now look like the image below.

Define Models

Whenever we want to receive or send information in a particular format (JSON) we accomplish this with the help of model. We specify the name of the model. Next, we describe the information it expects and the properties of each expected value.

model = app.model('Name Model', 
		  {'name': fields.String(required = True, 
					 description="Name of the person", 
help="Name cannot be blank.")})

We define the model name as Name Model. It includes one parameter, namely name which is a required field, and define its description and help text. The API which will use this model will expect a JSON with a key as name.

list_of_names = {}

To keep track of all names, I’ll store them in list_of_names.

Define APIs

@name_space.route("/<int:id>")
class MainClass(Resource):

	@app.doc(responses={ 200: 'OK', 400: 'Invalid Argument', 500: 'Mapping Key Error' }, 
			 params={ 'id': 'Specify the Id associated with the person' })
	def get(self, id):
		try:
			name = list_of_names[id]
			return {
				"status": "Person retrieved",
				"name" : list_of_names[id]
			}
		except KeyError as e:
			name_space.abort(500, e.__doc__, status = "Could not retrieve information", statusCode = "500")
		except Exception as e:
			name_space.abort(400, e.__doc__, status = "Could not retrieve information", statusCode = "400")

	@app.doc(responses={ 200: 'OK', 400: 'Invalid Argument', 500: 'Mapping Key Error' }, 
			 params={ 'id': 'Specify the Id associated with the person' })
	@app.expect(model)		
	def post(self, id):
		try:
			list_of_names[id] = request.json['name']
			return {
				"status": "New person added",
				"name": list_of_names[id]
			}
		except KeyError as e:
			name_space.abort(500, e.__doc__, status = "Could not save information", statusCode = "500")
		except Exception as e:
name_space.abort(400, e.__doc__, status = "Could not save information", statusCode = "400")

Let’s break down the code snippet above into smaller parts to understand it better. We’ll explore the POST endpoint. The functionality of GET would be very similar.

Define route and class

@name_space.route("/<int:id>")
class MainClass(Resource):

We use the name_space namespace to define the route i.e. [http://127.0.0.1:5000/main/<int:id>](http://127.0.0.1:5000/main/ "http://127.0.0.1:5000/main/<int:id>"). It expects an Id to be sent as an integer. The name of out class is MainClass which has one parameter, Resource.

Define docs for the API

@app.doc(responses={ 200: 'OK', 400: 'Invalid Argument', 500: 'Mapping Key Error' }, 
params={ 'id': 'Specify the Id associated with the person' })

Using doc we can define the documentation for the API in Swagger. The responses key defines the various possible HTTP Status Codes. For each status code, we also define a text that describes it to the user. The params key defines the expected parameter. The API expects id in the URL and we specify a help text for the user. The Swagger UI looks like the image below.

The parameters are defined in the top part. All the expected responses with their description appear in the lower part.

Define the method

@app.expect(model)		
def post(self, id):
  try:
    list_of_names[id] = request.json['name']
    return {
      "status": "New person added",
      "name": list_of_names[id]
    }
  except KeyError as e:
    name_space.abort(500, e.__doc__, status = "Could not save information", statusCode = "500")
  except Exception as e:
name_space.abort(400, e.__doc__, status = "Could not save information", statusCode = "400")

We can now define our method. Before our method, we add the line expect(model) which defines that the API expects model. We wrap our code inside a try block and catch all errors that might occur. The request.json['name] gets us the received name and we can save it as well as send it back in the response. If the name key is missing, we get KeyError and we send Status Code 500. In other cases, we send Status Code 400.

Try the App

Let’s start the app.

FLASK_APP=app.py flask run

POST

We parse the response from the request, read the name and store it against the id in list_of_names. We also return the status and the name of the newly added person.

Error in POST Request

Say, we forgot to supply the name parameter in the data object. In this case, we’ll get an error.

On not supplying the key name, we got an error with Status Code 500 and the message Mapping key not found.

GET

We just pass the id that we want to get the name for and we get the status and the name of the person back if available.

Error in GET Request

Say, we don’t have any person against Id 2. If we try to retrieve that information, it’ll throw an error.

As that specific Id is not found, we get Status Code 500 and the message Mapping key not found.

Conclusion

In this article, we explored creation of APIs using Flask and Flask-RESTPlus. Both of these are great libraries to develop as well as document APIs in Python and interact with APIs using Swagger.

Please feel free to share your thoughts and ideas.

#python #flask #rest #api