Javatpoint Logo
Javatpoint Logo

Python REST APIs with Flask, Connexion, and SQLAlchemy

Create a Virtual Environment:

In this tutorial, you will fabricate your undertaking structure. You can name the root envelope of your venture a way you like. For instance, you could name it rp_flask_api/. Make the organizer and explore into it:

Syntax to Create a Folder in the Shell:

Here, the mkdir represent the make directory Syntax in the command prompt

For this situation, you name the root organizer of your undertaking rp_flask_api/. The documents and envelopes that you make throughout this series will be situated in either this envelope or its subfolders.

After you explore to the venture organizer, it is smart to establish and initiate a virtual climate. Like that, you are introducing any task conditions not framework wide yet just in your venture's virtual climate.

Select your working framework beneath and utilize your foundation explicit order to set up a virtual climate:

Power shell:

With the orders displayed above, you establish and enact a virtual climate named venv by utilizing Python's underlying venv module. The parenthesized (venv) before the brief show that you have effectively enacted the virtual climate.

Adding Dependencies:

After you've established and enacted your virtual climate, now is the ideal time to introduce Carafe with pip:


The Flask miniature web structure is the primary reliance that your task requires. On top of Carafe, introduce Association with handle the HTTP demands:


To likewise utilize auto-produced Programming interface documentation, you introduce Association with the additional help for Strut UI. Later in this instructional exercise, you'll study the Python bundles that you recently introduced.

Initiate Your Flask Project:

The main document of your Flask project will be Make in rp_flask_api/and add the accompanying substance:


You import the Jar module, giving the application admittance to the Carafe usefulness. You then make a Carafe application case named application. Then, you associate the URL course "/" to the home() capability by improving it with @app.route("/"). This capability calls the Jar rend_template() capability to get the home.html record from the formats catalog and return it to the program.

To put it plainly, this code makes a fundamental web server ready and causes it to answer with a home.html format, which will be served to a program while exploring to the URL "/".

Note: Flask's improvement server defaults to port 5000. On fresher macOS renditions, this port is now being used by the macOS Air Play beneficiary. Above, you have changed the port of your Carafe application with port=8000. In the event that you need, you can change the Air Play collector inclinations on your Macintosh all things being equal.

Flask expects home.html in a format registry named layouts/. Make the layouts/catalog and add home.html:

Flask accompanies the Jinja Templating Motor, which empowers you to improve your layouts. However, your home.html format is an essential HTML record with no Jinja highlights. That is acceptable as far as now, in light of the fact that the motivation behind home.html is to check that your Jar project answers as expected.

With the Python virtual climate dynamic, you can run your application with this order line in the catalog containing the document:


At the point when you run, a web server will begin on port 8000. In the event that you open a program and explore to http://localhost:8000, you ought to see Hi, World!

Python REST APIs with Flask, Connexion, and SQLAlchemy

Adding Your First REST API Endpoint:

Now that you have a functioning web server, you can add your most memorable REST Programming interface endpoint. To do this, you will utilize Association, which you introduced in the past area.

The Association module permits a Python program to utilize the Open API particular with Strut. The Open API Particular is a Programming interface portrayal design for REST APIs and gives a ton of usefulness, including:

  • Approval of info and result information to and from your Programming interface
  • Setup of the Programming interface URL endpoints and the normal boundaries

At the point when you use Open API with Strut, you can make a UI (UI) to investigate the Programming interface. All of this can happen when you make a setup document that your Cup application can get to.

Create the API Configuration File:

The Strut design document is a YAML or JSON record containing your Open API definitions. This document contains all of the data important to design your server to give input boundary approval, yield reaction information approval, and URL endpoint definition.

Make a document named swagger.yml and start adding metadata to it:

At the point when you characterize a Programming interface, you should incorporate the adaptation of your Open API definition. You utilize the openapi catchphrase for this. The rendition string is significant in light of the fact that a few pieces of the Open API construction might change after some time.

Additionally, very much like each new Python variant incorporates new highlights, there might be watchwords added or censured in the Open API detail.

The data watchword starts the extent of the Programming interface data block:

  • Title: Title remembered for the Association produced UI framework
  • Description: Portrayal of what the Programming interface gives or is about
  • Version: Variant incentive for the Programming interface

Then, add servers and url, which characterize the root way of your Programming interface:

By giving "/programming interface" as the worth of url, you'll have the option to get to every one of your Programming interface ways comparatives with http://localhost:8000/programming interface.

You characterize your Programming interface endpoints in a ways block:

The ways block starts the arrangement of the Programming interface URL endpoint ways:

  • /individuals: The general URL of your Programming interface endpoint
  • get: The HTTP strategy that this URL endpoint will answer

Along with the url definition in servers, this makes the GET/programming interface/individuals URL endpoint that you can access at http://localhost:8000/programming interface/individuals.

The get block starts the design of the single/programming interface/individuals URL endpoint:

  • operationId: The Python capability that will answer the solicitation
  • labels: The labels doled out to this endpoint, which permit you to bunch the activities in the UI
  • synopsis: The UI show text for this endpoint
  • reactions: The status codes that the endpoint answers with

operationId should contain a string. Association will utilize "people.read_all" to find a Python capability named read_all() in a group module of your undertaking. You'll make the relating Python code later in this instructional exercise.

The reactions block characterizes the setup of the conceivable status codes. Here, you characterize a fruitful reaction for the status code "200", containing some depiction text.

You can find the total substance of the swagger.yml document in the folding beneath:

The swagger.yml document resembles a plan for your Programming interface. With the details that you remember for swagger.yml, you characterize what information your web server can expect and how your server ought to answer demands. However, up to this point, your Cup project has barely any insight into your swagger.yml document. Peruse on to utilize Association with interface your OpenAPI detail with your Flagon application.

Add Connexion to the App:

There are two moves toward adding a REST Programming interface URL endpoint to your Flagon application with Association:

  • Add a Programming interface design document to your undertaking.
  • Interface your Flagon application with the arrangement document.

You previously added a design document named swagger.yml in the last segment. To associate the Programming interface setup record with your Cup application, you should reference swagger.yml in your document:

The import association explanation adds the module to the program. The following stage is making the application case utilizing Association as opposed to Carafe. Inside, the Cup application is as yet made, however it presently has extra usefulness added to it.

Part of the application occasion creation incorporates the boundary specification_dir in line 6. This advises Association which registry to search in for its setup record. For this situation, it is the very index that you run from.

In line 7, you advise the application occurrence to peruse the swagger.yml document from the detail catalog and arrange the framework to give the Association usefulness.

Return Data from your People Endpoint:

In the swagger.yml document, you arranged Association with the operation Id esteem "people.read_all". Thus, when the Programming interface gets a HTTP demand for GET/programming interface/individuals, your Cup application calls a read_all() capability inside a group module.

To make this work, make a document with a read_all() capability:

In line 5, you make a partner capability named get_timestamp() that creates a string portrayal of the current timestamp.

You then, at that point, characterize Individuals word reference information structure in line 8, which is the information you'll work with in this piece of the instructional exercise series.

Individuals word reference subs for a legitimate data set. As Individuals is a module variable, its state continues between REST Programming interface calls. Notwithstanding, any information that you change will be lost when you restart your web application. This isn't great, however it's fine for the present.

Then, at that point, you make the read_all() capability in line 26. Your server will run read_all() when it gets a HTTP solicitation to GET/programming interface/individuals. The return worth of read_all() is a rundown of word references with data about an individual.

Running your server code and exploring your program to http://localhost:8000/programming interface/individuals will show the rundown of individuals on-screen:

Python REST APIs with Flask, Connexion, and SQLAlchemy

Explore your API Documentation:

As of now you have a REST Programming interface running with a solitary URL endpoint. Your Cup application knows what to serve in light of your Programming interface determination in swagger.yml. Also, Association involves swagger.yml to make Programming interface documentation for you.

Explore to localhost:8000/programming interface/ui to see your Programming interface documentation in real life:

Python REST APIs with Flask, Connexion, and SQLAlchemy

This shows the construction of the normal reaction, the substance sort of that reaction, and the portrayal text that you entered about the endpoint in the swagger.yml document. Any time the setup document changes, the Strut UI changes also.

You might give the endpoint a shot by tapping the Give it a shot button. This element can be very valuable when your Programming interface develops. The Strut UI Programming interface documentation gives you a method for investigating and examination with the Programming interface without composing any code to do as such.

Utilizing OpenAPI with the Strut UI offers a decent, clean method for making the Programming interface URL endpoints. Up until this point, you've just made one endpoint to serve all individuals. In the following segment, you'll add extra endpoints to make, update, and erase individuals in your assortment.

Building Out the Complete API:

Up until this point, your Flagon REST Programming interface has one endpoint. Presently it is the ideal time to work out a Programming interface giving full Muck admittance to your kin structure. As you review, the meaning of your Programming interface seems to be this:

Action HTTP Verb URL Path Description

Read GET /programming interface/people Read is used as an assortment of individuals.

Create POST /programming interface/people Create is used as a renewed individual.

Read GET /programming interface/individuals/<lname> Read is used as a specific individual.

Update PUT /programming interface/individuals/<lname> Update is used as a current individual.

Delete DELETE /programming interface/individuals/<lname> Delete a current individual.

Work with Components:

Before you characterize new Programming interface ways in swagger.yml, you will add another block for parts. Parts are building blocks in your Open API detail that you can reference from different pieces of your determination.

Add a parts block with outlines for a solitary individual:

To stay away from code duplication, you make a parts block. Until further notice, you save just the Individual information model in the blueprints block:

type: The information sort of the outline

required: The necessary properties

Scramble (- ) before - lname demonstrates that required can contain a rundown of properties. Any property that you characterize as required should likewise exist in properties, which incorporates the accompanying:

fname: The primary name of an individual

lname: The last name of an individual

The sort key characterizes the worth related with its parent key. For Individual, all properties are strings. You will address this blueprint in your Python code as a word reference later in this instructional exercise.

Create a New Person:

Expand your Programming interface endpoints by adding another block for the post demand in the/individuals block:

The construction for present seems to be comparable on the current get composition. One distinction is that you likewise send request Body to the server. All things considered; you want to tell Carafe the data that it needs to make a renewed individual. One more distinction is operation Id, which you set to people.create.

Within satisfied, you characterize application/json as the information trade configuration of your Programming interface.

You can serve various media types in your Programming interface solicitations and Programming interface reactions. These days APIs generally use JSON as the information trade design. This is uplifting news for you as a Python engineer, on the grounds that JSON objects seem to be Python word references. For instance:


This JSON object looks like the Individual part that you were characterizing before in swagger.yml and that you're referring to with $ref in diagram.

You are likewise utilizing a 201 HTTP status code, which is a triumph reaction that demonstrates the production of another asset.

Note: If you need to get familiar with HTTP status codes, then you can look at Mozilla's documentation about HTTP reaction status codes.

With people.create, you're advising your server to search for a make() capability in individuals module. Open and add make() to the record:

In line 4, you're bringing in Jar's cut short () capability. Utilizing cut short () assists you with sending a mistake message in line 20. You raise the mistake reaction when the solicitation body doesn't contain a last name or when an individual with this last name as of now exists.

Note: An individual's last name should be interesting, on the grounds that you're utilizing lname as a word reference key of Individuals. That implies you cannot have two individuals with a similar last name in your venture for the time being.

On the off chance that the information in the solicitation body is substantial, you update Individuals in line 13 and answer with the new item and a 201 HTTP code in line 18.

Handle a Person:

Up until this point, you are ready to make a renewed individual and get a rundown with every one of your kin. In this part, you'll refresh swagger.yml and to work with another way that handles a solitary existing individual.

Open swagger.yml and add the code underneath:

Like your/individuals way, you start with the get activity for the/individuals/{lname} way. The {lname} substring is a placeholder for the last name, which you need to pass in as a URL boundary. In this way, for instance, the URL way programming interface/individuals/Ruprecht contains Ruprecht as lname.

Note: The URL boundaries are case delicate. That implies you should type a last name like Ruprecht with a capitalized R.

You will utilize the lname boundary in different tasks, as well. So, it's a good idea to make a part for itself and reference it where required.

Here, operationId focuses to a read_one () capability in, so go to that record once more and make the missing capability:

At the point when your Cup application finds the gave last name in Individuals, then, at that point, it returns the information for this specific individual. If not, the server will return a 404 HTTP blunder.

To refresh a current individual, update swagger.yml with this code:

With this meaning of the put activity, your server anticipates update() in

The update() capability expects the contentions lname and individual. At the point when an individual with the gave last name exists, then you update the comparing values in Individuals with the individual information.

To dispose of an individual in your dataset, you really want to work with an erase activity:

Add the comparing erase() capability to

To erase exists in your dataset, then, at that point, you eliminate the thing from Individuals.With every one of the endpoints to oversee individuals set up, now is the ideal time to evaluate your Programming interface. Since you utilized Association with interface your Flagon project with Strut, your Programming interface documentation is prepared for you when you restart your server.

Whenever you've refreshed the swagger.yml and documents to finish individuals Programming interface usefulness, the Strut UI framework will refresh as needs be. This UI permits you to see all of the documentation that you've remembered for the swagger.yml record and to communicate with all of the URL endpoints making up the Muck usefulness of individual's interface.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA