tutorial101 is the one place for high quality web development, Web Design and software development tutorials and Resources programming. Learn cutting edge techniques in web development, design and software development, download source components and participate in the community.
REST API Query Parameter GET Request using Python Flask and PostgreSQL Database
Create table
CREATE TABLE useraccount (
id serial PRIMARY KEY,
username VARCHAR ( 100 ) NOT NULL,
password VARCHAR ( 100 ) NOT NULL
);
Insert data
INSERT INTO useraccount (username, password) VALUES ('tutorial101', 'pbkdf2:sha256:150000$KxxiGerN$4c37a656baa0034035a6be2cd698b5da8b036ae63eef3ab0b08b9c18b9765648');
Testing Rest API
REST API Testing is open-source web automation testing technique that is used for testing RESTful APIs for web applications. The purpose of rest api testing is to record the response of rest api by sending various HTTP/S requests to check if rest api is working fine or not. Rest api testing is done by GET, POST, PUT and DELETE methods.
Rest stands for Representational State Transfer. It is an architectural style and an approach for communication used in the development of Web Services. REST has become a logical choice for building APIs. It enables users to connect and interact with cloud services efficiently.
An API or Application Programming Interface is a set of programming instructions for accessing a web-based software application.
API is a set of commands used by an individual program to communicate with one another directly and use each other's functions to get information.
Install the Advanced Rest Client
1. Go to Google Chrome's Web Store
2. Search for "Advanced Rest Client" https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo and Install the extension
REST API Testing is open-source web automation testing technique that is used for testing RESTful APIs for web applications. The purpose of rest api testing is to record the response of rest api by sending various HTTP/S requests to check if rest api is working fine or not. Rest api testing is done by GET, POST, PUT and DELETE methods.
Rest stands for Representational State Transfer. It is an architectural style and an approach for communication used in the development of Web Services. REST has become a logical choice for building APIs. It enables users to connect and interact with cloud services efficiently.
An API or Application Programming Interface is a set of programming instructions for accessing a web-based software application.
API is a set of commands used by an individual program to communicate with one another directly and use each other's functions to get information.
Install the Advanced Rest Client
1. Go to Google Chrome's Web Store
2. Search for "Advanced Rest Client" https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo and Install the extension
#app.py
from flask import Flask, jsonify, request, session
from werkzeug.security import generate_password_hash, check_password_hash
from flask_cors import CORS #pip install -U flask-cors
from datetime import timedelta
import psycopg2 #pip install psycopg2
import psycopg2.extras
app = Flask(__name__)
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=10)
CORS(app)
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
@app.route('/')
def home():
passhash = generate_password_hash('cairocoders')
print(passhash)
if 'username' in session:
username = session['username']
return jsonify({'message' : 'You are already logged in', 'username' : username})
else:
resp = jsonify({'message' : 'Unauthorized'})
resp.status_code = 401
return resp
@app.route('/login', methods=['POST'])
def login():
_json = request.json
_username = _json['username']
_password = _json['password']
print(_password)
# validate the received values
if _username and _password:
#check user exists
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
sql = "SELECT * FROM useraccount WHERE username=%s"
sql_where = (_username,)
cursor.execute(sql, sql_where)
row = cursor.fetchone()
username = row['username']
password = row['password']
if row:
if check_password_hash(password, _password):
session['username'] = username
cursor.close()
return jsonify({'message' : 'You are logged in successfully'})
else:
resp = jsonify({'message' : 'Bad Request - invalid password'})
resp.status_code = 400
return resp
else:
resp = jsonify({'message' : 'Bad Request - invalid credendtials'})
resp.status_code = 400
return resp
@app.route('/logout')
def logout():
if 'username' in session:
session.pop('username', None)
return jsonify({'message' : 'You successfully logged out'})
if __name__ == "__main__":
app.run()
SwiftUI Blog Post Screen Stretchy header with parallax scrolling effectContentView.swift
//
// ContentView.swift
// Test
//
// Created by Cairocoders
//
import SwiftUI
struct ContentView: View {
let articleContent =
"""
Ang Bayan ng El Nido ay isang bayan at marine reserve park sa lalawigan ng Palawan, Pilipinas. Ito ay may 420 kilometrong layo sa timog-kanluran ng Maynila. Ayon sa senso ng 2015, ito ay may populasyon na 41,606 sa may 9,465 na kabahayan. 85% ng mga tao dito ay naninirahan sa mga bukirin, samantalang 15% na nalalabi ay makikita sa Población (town proper).
Ang bayan ay makikita sa pinakahilagang dulo ng pulo ng Palawan. Ito ay binubuo ng 45 na mga pulo na may iba't ibang itsura at porma. Katulad ng kabuuang Palawan, ang El Nido ay kabilang sa Eurasian Plate, isang plate na hiwalay sa Philippine Plate na siyang kinabibilangan ng kabuuang bansa. Ang mga limestone cliffs na matatagpuan dito ay katulad ng mga matatagpuan sa Ha Long Bay sa Vietnam, Krabi sa Tailanda at Guillin sa Tsina na bahagi rin ng Eurasian Plate.
"""
var body: some View {
ScrollView {
GeometryReader { geometry in // Implement Parallax Scrolling Header
VStack {
if geometry.frame(in: .global).minY <= 0 {
Image("banner")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: geometry.size.width, height: geometry.size.height)
.offset(y: geometry.frame(in: .global).minY/9)
.clipped()
} else {
Image("banner")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: geometry.size.width, height: geometry.size.height + geometry.frame(in: .global).minY)
.clipped()
.offset(y: -geometry.frame(in: .global).minY)
}
}
}
.frame(height: 400)
VStack(alignment: .leading) {
HStack {
Image("photo1")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 60, height: 60)
.clipped()
.cornerRadius(10)
VStack(alignment: .leading) {
Text("Article by")
.font(.title3)
.foregroundColor(.gray)
Text("Cairocoders")
.font(.title3)
}
}
.padding(.top, 20)
Text("El Nido Palawan")
.font(.largeTitle)
.lineLimit(nil)
.padding(.top, 10)
Text("23 min read • 22. July 2020")
.font(.title3)
.foregroundColor(.gray)
.padding(.top, 10)
Text(articleContent)
.font(.title2)
.lineLimit(nil)
.padding(.top, 30)
}//End VStack
.frame(width: 350)
}
.edgesIgnoringSafeArea(.top)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
SwiftUI How to Fetch Json data and display it into a list and show details view
Goto to the https://jsonplaceholder.typicode.com/users we use this JSON URL to display the data
ContentView.swift
//
// ContentView.swift
// Test
//
// Created by Cairocoders
//
import SwiftUI
struct ContentView: View {
@State var users: [User] = []
var body: some View {
NavigationView {
List(users) { user in
NavigationLink(destination: DetailsView(userItem: user)) {
HStack {
Text(user.name)
.font(.headline)
}.padding(7)
}
}
.navigationBarTitle("Fetch JSON data")
.onAppear {
apiCall().getUsers { (users) in
self.users = users
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
DetailsView.swift
//
// DetailsView.swift
// Test
//
// Created by Cairocoders
//
import SwiftUI
struct DetailsView: View {
let userItem: User
var body: some View {
VStack(alignment: .leading) {
VStack {
Text(userItem.name)
.font(.title2)
.multilineTextAlignment(.leading)
Text("Username: \(userItem.username)")
.font(.title2)
.multilineTextAlignment(.leading)
Text("Email: \(userItem.email)")
.font(.title2)
.multilineTextAlignment(.leading)
}
Spacer()
}
.padding()
.navigationBarTitle(Text(userItem.name), displayMode: .automatic)
}
}
ViewModel.swift
//
// ViewModel.swift
// Test
//
// Created by Cairocoders
//
import Foundation
class apiCall {
func getUsers(completion:@escaping ([User]) -> ()) {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
let users = try! JSONDecoder().decode([User].self, from: data!)
//print(users)
DispatchQueue.main.async {
completion(users)
}
}
.resume()
}
}
Model.swift
//
// Model.swift
// Test
//
// Created by Cairocoders
//
import Foundation
struct User: Codable, Identifiable {
let id: String = UUID().uuidString
let username: String
let name: String
let email: String
private enum CodingKeys: String, CodingKey {
case id
case name
case username
case email
}
}
SwiftUI’s fullScreenCover() modifier gives us a presentation style for times when you want to cover as much of the screen as possible, and in code it works almost identically to regular sheets.
ContentView.swift
//
// ContentView.swift
// Test
//
// Created by Cairocoders
//
import SwiftUI
struct ContentView: View {
@State private var isPresented = false
var body: some View {
Button("Present!") {
isPresented.toggle()
}
.fullScreenCover(isPresented: $isPresented, content: FullScreenModalView.init)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct FullScreenModalView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
Text("modal view")
Button("Dismiss Modal") {
presentationMode.wrappedValue.dismiss()
}
}
}
SwiftUI Recipe App Using Carousel List and Grid with Details View
In this tutorial I'm going to show how to create a recipe app with carousel list and grid
ContentView.swift
//
// ContentView.swift
// Test
//
// Created by Cairocoders
//
import SwiftUI
struct ContentView: View {
var body: some View {
Home()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Home : View {
@State var search = ""
@State var index = 0
@State var columns = Array(repeating: GridItem(.flexible(), spacing: 15), count: 2)
var body: some View{
ScrollView(.vertical, showsIndicators: false) {
LazyVStack{
HStack{
Text("Recipes")
.font(.title)
.fontWeight(.bold)
Spacer()
}
.padding(.horizontal)
TextField("Search", text: self.$search)
.padding(.vertical,10)
.padding(.horizontal)
.background(Color.black.opacity(0.07))
.cornerRadius(10)
.padding(.horizontal)
.padding(.top,25)
// Carousel List...
TabView(selection: self.$index){
ForEach(1...5,id: \.self) {index in
Image("banner\(index)")
.resizable()
// adding animation...
.frame(height: self.index == index ? 230 : 180)
.cornerRadius(15)
.padding(.horizontal)
// for identifying current index....
.tag(index)
}
}
.frame(height: 230)
.padding(.top,25)
.tabViewStyle(PageTabViewStyle())
.animation(.easeOut)
// adding custom Grid....
HStack{
Text("Popular")
.font(.title)
.fontWeight(.bold)
Spacer()
Button {
// reducing to row.....
withAnimation(.easeOut){
if self.columns.count == 2{
self.columns.removeLast()
}
else{
self.columns.append(GridItem(.flexible(), spacing: 15))
}
}
} label: {
Image(systemName: self.columns.count == 2 ? "rectangle.grid.1x2" : "square.grid.2x2")
.font(.system(size: 24))
.foregroundColor(.black)
}
}
.padding(.horizontal)
.padding(.top,25)
LazyVGrid(columns: self.columns,spacing: 25){
ForEach(data){recipe in
// GridView....
PopularRecipes(recipes: recipe,columns: self.$columns, setid: recipe.id) //PopularRecipes.swift
}
}
.padding([.horizontal,.top])
}
.padding(.vertical)
}
.background(Color.black.opacity(0.05).edgesIgnoringSafeArea(.all))
}
}
Recipes.swift
//
// Recipes.swift
// Test
//
// Created by Cairocoders
//
import Foundation
struct Recipe : Identifiable {
var id : Int
var name : String
var image : String
var rating : Int
var details : String
}
var data = [
Recipe(id: 0, name: "Bistek Tagalog", image: "recipe1", rating: 2, details: "A dish made of strips of salted and peppered sirloin beef, usually flattened with a meat tenderizing tool, slowly cooked in soy sauce, calamansi juice, garlic and onions, a specialty of the Tagalog region"),
Recipe(id: 1, name: "Boogie flight", image: "recipe2", rating: 5, details: "A boodle fight is a meal that dispenses with cutlery and dishes. Diners instead practice kamayan, Filipino for eating with the hands"),
Recipe(id: 2, name: "Sinigang Na Baboy", image: "recipe3", rating: 3,details: "Sinigang na baboy with Gabi is a Filipino pork soup with taro cooked in a sour broth."),
Recipe(id: 3, name: "Ginisang Togue", image: "recipe4", rating: 2,details: "Ginisang Togue is basically Sauteed Mung Bean Sprout with carrots, bell pepper, shrimp, and tofu."),
Recipe(id: 4, name: "Ginisang Munggo (Monggo)", image: "recipe5", rating: 4, details: "Munggo or Mung bean (or even green bean to some) is a seed of Vigna radiata, a plant native to India and Pakistan. Since the plant originated in Asia, it was easy to spread along the nearby countries. This seed became a hit when it reached the Philippines."),
Recipe(id: 5, name: "Pork Estofado (Sweet Pork Stew)", image: "recipe6", rating: 2, details: "Pork Estofado with saba bananas, carrots, Chinese sausage, and a sweet and savory sauce. Perfect with steamed rice!"),
Recipe(id: 6, name: "Pata Tim", image: "recipe7", rating: 4, details: "Brimming in a pork stew infused with aromatic peppercorn, sesame oil and soy sauce, Pata Tim is a classic Filipino dish with traces in Chinese cuisine"),
Recipe(id: 7, name: "Pancit Palabok", image: "recipe8", rating: 3, details: "Pancit Palabok is a noodle dish with shrimp sauce and topped with several ingredients such as cooked shrimp, boiled pork, crushed chicharon, tinapa flakes, fried tofu, scallions, and fried garlic. "),
]