fabiochiu/medium-articles huggingface dataset:
Salesforce to Salesforce Integration using Named Credentials
By: Konrad Kowalewski
Tags: Integration, Rest Api, Sfdc, API, Salesforce

Today, I would like to show how to integrate two Salesforce organization base on Named Credentials. First of all we will start with benefits which we can achieve implement this in our project. Second part will be focused on practical approach.

Benefits

It is easy to implement and maintenance if an endpoint URL changes, you update only the named credential, and should work fine. You can deploy the Named Credentials to every orgs and each org can have a different endpoint URL. Apex class can be deployed to those orgs without worry to reference to the wrong endpoint and another related configuration because every information about integration is stored in Named Credentials. By Using Named Credential, we can make a call out to an external system without supplying a username or password in the code. You can use many authentication protocols as Password, OAuth 2.0, JWT, JWT Token Exchange, AWS Signature Version 4 more (https://help.salesforce.com/articleView?id=named_credentials_auth_protocols.htm). We can customize our request header and body base on using these merge fields in your Apex code (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials_merge_fields.htm). Adding a remote site is not required, for the site defined in the named credential.

Time to practice

I will show you a basic example step by step how to integrate two Salesforce organizations using Named Credentials.

Create Connected App:
REST API — Interview Preparation. It is commonly known that many…
By: Fidan Musazade
Tags: API, Rest Api, Web Development, Web Services

Source: Seobility

It is commonly known that many programming interviews may include questions related to APIs, and most probably REST API. So this article aims to give you five possible questions and answers to expect at an interview. Enjoy! :)

1.What is the REST API?

In short, REST stands for Representational State Transfer. This is a set of guidelines to use when developing a web service. Those services that comply with these guidelines are called RESTful services. There are six main principles of a REST architecture:

There is a division between client and server

REST API is stateless

It is cacheable

The interface is uniform

The system is hierarchically layered

Optional: code on demand

2. What are the differences between REST and SOAP?

SOAP stands for Simple Object Access Protocol. Key differences:

While SOAP is a protocol, REST is rather an architectural pattern.

SOAP requires more bandwidth than REST.

SOAP is compatible with XML, while REST can work with text, XML, HTML, and JSON.

SOAP cannot usee REST, while REST can use SOAP.

SOAP cannot be cached, while REST can.

There are also other minor differences, but these should be enough to note.

3. What are the benefits of REST API?

First of all, as the client and the server are clearly separated, it becomes easier to scale the application up and add new functionality. Furthermore, portability to other platforms is also improved by this.

Secondly, the separation mentioned above makes the application more reliable and the possibility to easily scale. This advantage also concern the independence of API. It is independent and can work on any platform. For example, you can use Python, PHP, Java and other servers.

4. Name some of REST API security threats

Injection attacks

DoS attacks

Broken authentication

Sensitive data exposure

Broken access control, etc.

5. What is a “Resource” in RESTful web services?

Anything that can be named. Example: document, image, virtual object, etc. Resource identifier is used to name a particular resource. Resources also have resource representations. This is data, metadata and hypermedia links associated with a resource at a given time.
Fuzzing your own API with RESTler
By: Arthur Moreira
Tags: Restler, Microsoft, Fuzzing, Rest Api, Fuzz Testing

Fuzz testing is a technique used to find faults in a software. It uses a heavy volume of data as the inputs to analyze the different paths the software can guide.

Microsoft recently released RESTLer, a fuzzing tool for automate tests for a REST API, in order to find security bugs in it. If used side-by-side with the developing process, those tests can guide the development team to prevent or fix a lot of potential unwelcome obstacle.

To install it, you’ll need: Python 3.8.1 and .NET core SDK 3.1.

First, I cloned the restler-fuzzer repo. Then, I created a directory to build RESTler inside it.

mkdir C:\RESTler python <full path to restler-fuzzer repo>/build-restler.py --dest_dir C:\RESTler

From now on, I am using the GhibliAPI, a simple API for Studio Ghibli movies. This API was developed with Django Rest Framework. You can clone GhibliAPI repo to your computer and run as a local server (the instructions are in the README.md file), or you can choose any other REST API you want!

Tip: With json-server you can emulate a REST API with zero coding, just using a JSON file as your data.

There are three endpoints in this API.

This API is also featured with a Swagger/OpenAPI 2.0 specification page. It was automatically generated by the awesome lib drf-yasg.

By addind /?format=openapi to the end of the Swagger url, it shows a JSON. Save the content into a new file named swagger.json. The swagger.json file now encapsulates all the information that RESTler need for it to be aware of what to do with that API.
How to get Azure REST APIs access tokens using PowerShell — Update (November 26, 2020)
By: Dmitri Gaikovoi
Tags: Security, Token, Rest Api, Azure, Powershell

How to get Azure REST APIs access tokens using PowerShell — Update (November 26, 2020) Dmitri Gaikovoi ·Nov 26, 2020

Since the release of Az module version 5.x, cmdlet Get-AzContext doesn’t populate TokenCache property anymore. New cmdlet Get-AzAccessToken, avalable starting Az v 5.1.0, can be used now to acquire access tokens:
REST API: File Upload Handling
By: Girija Shankar Behera
Tags: Programming Rest Apis, Rest Api, PROGRAMMING REST APIS, REST APIs, Django Rest Framework

In the code snippet, we see that the default parser is changed to a list containing only FileUploadParser now. And there was no error as well, as the API was able to understand the data in the request. Still I had to do one more update here in the client side, i.e. there is no way the API is going to get the name of the file, so it won’t be able to access the file, unless we have a way of providing the name externally. So we add another header for the file name like this: ‘Content-Disposition: attachment; filename=healthy_leaves_1.png’.

This made sure that the API gets to know the name of the file, and gets access to it from the request.

Well, this only ensures that the API knows that the request has a file type of data in it. Backend still needs to handle the specific file uploads depending on their types. Like in the request above, we are sending an image file. To read this, we still need to use the Image libraries available in Python.
REST API Fuzzing with Microsoft RESTLer
By: Geraldo Galvão
Tags: Fuzzing, Rest Api, Testing

Since we are running locally on a sample code, this warning will not impact us, but please be careful, and don’t run RESTLer if you are targeting a deployed application which don’t belongs to you.

The commands for the Fuzz-lean and Fuzz modes are, respectively:

.\restler fuzz-lean --grammar_file <full path to grammar.py> --dictionary_file <full path to dict.json> --settings <full path to engine_settings.json> --no_ssl .\restler fuzz --grammar_file <full path to grammar.py> --dictionary_file <full path to dict.json> --settings <full path to engine_settings.json> --no_ssl --time_budget <time in hours to run>

When the run is finished, RESTLer will print the Coverage results, and the sum of the bugs. All bugged request sequences will be placed in: FuzzLean or Fuzz folders. My 1 hour fuzz run gave this result:

PayloadBodyChecker_500: 33 main_driver_500: 10

So, what is the PayloadBodyChecker above? Checkers in RESTLer do exactly what they say. These are run alongside the normal fuzzing and can check if there is more bugs, each runs with a different logic. In our case, it detected 33 bugs fuzzing directly the JSON body of our request. Other 10 bugs were found on the normal fuzzing run, every time there is a 500 response, it will be treated as a bug.

Let’s look now our bug buckets, inside Fuzz/RestlerResults/experiment<…>/bug_buckets is the collection of all bugged requests with theirs respective responses. Having a look in the main_driver_500_1.txt file:

... -> POST /api/v3/user HTTP/1.1\r

Accept: application/json\r

Host: localhost:8080\r

Content-Type: application/json\r

\r

{

"id":0,

"username":"fuzzstring",

"firstName":"fuzzstring",

"lastName":"fuzzstring",

"email":"fuzzstring",

"password":"fuzzstring",

"phone":"fuzzstring",

"userStatus":0}\r

! producer_timing_delay 0 ! max_async_wait_time 20 PREVIOUS RESPONSE: 'HTTP/1.1 500 Internal Server Error\r

Date: Sun, 22 Nov 2020 19:36:09 GMT\r

Access-Control-Allow-Origin: *\r

Access-Control-Allow-Methods: GET, POST, DELETE, PUT\r

Access-Control-Allow-Headers: Content-Type, api_key, Authorization\r

Access-Control-Expose-Headers: Content-Disposition\r

Content-Type: application/json\r

Content-Length: 110\r

Server: Jetty(9.4.9.v20180320)\r

\r

{"code":500,"message":"There was an error processing your request. It has been logged (ID: 9b4a940aedfc92d9)"}'

As you can see the above request returns a Internal Server Error, RESTLer even gives you the option to replay the request with the — replay_log <path_to_the_log> command. It’s very useful to debug the error.
NetCore REST API/Dapper/SQLKata with VS Template KissApi
By: Fuji Nguyen
Tags: Genfu, Clean Architecture, Rest Api, Swagger, Dapper

Generate a New REST API Project with KissApi Template

The easiest way to create a new project is to start from a project template for a particular type of application or website. A project template consists of a basic set of pre-generated code files, config files, assets, and settings.

When you first open Visual Studio, the start window appears, and from there, you can choose to create a new project.

If the Visual Studio development environment is already open, you can create a new project by choosing File > New > Project on the menu bar or by clicking the New Project button on the toolbar.

Task 1 — Select a Template Type

On the Create a new project page, a list of your recently selected templates appears on the left. The templates are sorted by most recently used.

If you’re not selecting from the recently used templates, you can filter all available project templates by entering search text into the search box to further filter the templates.

Task 2— Create a Solution

On the Create a new project screen, search for the “KissApi” template and click on the Next button

Enter the project name (ex. MyProject) and click on the Create button

Right-mouse click on MyProject.WebApi and Set as Startup Project

Hit F5 to run. The swagger should show in the browser

Run the SQL script below to create a database and table object. Notice that you may need to change the database name to match with the one in your appsettings.json in the WebApi project.

KissAPI Template Screencast

Check out the complementary screencast showing

Scaffolding new project using the Visual Studio template KissAPI Browsing thru source code organization in the Clean Architecture solution Demonstration of REST API via Swagger

Check out related tutorials

Summary

When managing the development, many organizations are struggling with governance and look for value-added process improvement tools. The KissApi template increases consistency while decreases delivery times.

In case you want to know how to secure the REST API project with oAuth2, check out my other tutorials DevKit WebAPI Security.

Have a great REST!
Circuit Breaker Design Pattern
By: Escuela Technologies
Tags: Netflix Hystrix, Circuit Breaker, Spring Boot, Rest Api, Java Design Pattern

Wikipedia says Circuit breaker is a design pattern used in modern software development. It is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties.

Advantage of Circuit Breaker Pattern

Circuit Breaker allows graceful handling of failed remote services. The pattern is very handy when all parts of our application are extremely decoupled from each other, and also when one component is out of service doesn’t mean the other parts will stop working.

Handle costly remote service calls in such a way that the failure of a single service/component cannot bring the entire system down, and we can reconnect to the service once it is restored.

These days it is very common for software systems to make remote calls to software running in different processes, probably on different machines across a network. One of the big differences between in-memory calls and remote calls is that remote calls can fail, or hang without a response until some timeout limit is reached. What’s worse if you have many callers on an unresponsive supplier, then you can run out of critical resources leading to cascading failures across multiple systems

The basic idea behind the circuit breaker is pretty simple. You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain limit, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all. Usually, you might need some type of alert mechanism if the circuit breaker trips.

A service client should invoke a remote service via a proxy that functions in a similar fashion to an electrical circuit breaker. When the number of consecutive failures crosses a threshold, the circuit breaker trips, and for the duration of a timeout period all attempts to invoke the remote service will fail immediately. After the timeout expires the circuit breaker allows a limited number of test requests to pass through. If those requests succeed the circuit breaker resumes normal operation. Otherwise, if there is a failure the timeout period begins again

There are multiple implementations of the Circuit Breaker Design pattern in Java. Spring provides some perfect integration of this design pattern using Hystrix

Listed down some great implementation of Circuit Breaker pattern in Java. Take a look at those.

If you like this article please give a cheer !!
GraphQL —My Thoughts
By: Priyanshu Saraf
Tags: JavaScript, Restapi, GraphQL, Backenddevelopment

GraphQL is a hot and trendy topic currently, and it is growing very fast. There is a very good reason for that. I believe that GraphQL has a bright future ahead, and we will be discussing that in this article.

Prerequisites:

Basic JavaScript knowledge

Some familiarity with node JS or APIs in general

What Is GraphQL?

GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.

It is a very less used tool in your belt, but when the time comes, there is no other savior but it.

If you have dealt with Rest APIs, then I believe you know about the get, post, and delete requests. Here, GraphQL can make your life easier.

When you pass a request in a large scale application, you are serving a LOT of people, say 40 million-100 million or more. Here, just one request can become a big pain for you as this will put a lot of load on your servers. If you have a small scale, or even a relatively large scale application, which is serving say 3 million people at max, then this is not that big of a deal, but when you serve hundreds of millions of people, it becomes important for you to handle these requests efficiently. This is where GraphQL comes in.

Facebook was experiencing the problem of overloaded servers, and hence, they decided to create GraphQL, which would let them manage their requests efficiently. It helps you to take the exact piece of data that you need, and hence reduces a lot of load from the servers.

Although, even with all its benefits, GraphQL comes with its own set of cons

Cons:

You create a lot of mess in the backend,

A ton of configuration needed

Really not necessary for sites that are not handling a huge amount of traffic

GraphQL has a bunch of other stuff that makes it unique and powerful. In this blog, we will not be exploring a lot about it. This was centered around making you understand what graphQL exactly is.

My Thoughts

I believe that GraphQL is a very powerful, yet quite an unused tool that comes in handy only a few times. In my opinion, it is not something that I would focus on primarily if I were to become a full-stack developer. It is something that I would only have on my side, maybe spend just a bit if I need to. It is not the most important thing.

If you are an advanced developer, though, make sure to learn it. If it blows up, then you, being someone who already knows about it can charge people a lot to teach it to them, but if it does not, you learned something new. You took action, and maybe someday you might use it.

Thank you! I hope you found value in this article.

Priyanshu Saraf.
Learn about FastAPI
Tags: Rest Api, Fastapi

When it comes to application development using Python, Flask and Django have been our go-to. They are the two most used Python frameworks. But now there is this relatively new Python framework called FastAPI. It has very extensive documentation and rich examples, which makes things easier.

What is a REST API?

REST determines what the API looks like. It stands for “Representational State Transfer”. It is a set of rules that developers follow when they create their API. Rest API is a software that enables applications to communicate with a database or other software effectively.

What is FastAPI?

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

FastAPI is a Python framework with a set of tools that enables developers to use a REST interface to call commonly used functions to implement applications. It is accessed through a REST API to call common building blocks for an app.

FastAPI is a Python API microframework built on top of Starlette, Pydantic, and Uvicorn.

Why FastAPI?

Interactive API docs: FastAPI comes with interactive API docs, the automatic interactive API documentation being Swagger UI and the alternative being Redoc. It has a simple, but an elegant interface that creates an API document on the fly.

FastAPI comes with interactive API docs, the automatic interactive API documentation being Swagger UI and the alternative being Redoc. It has a simple, but an elegant interface that creates an API document on the fly. REST API Endpoints: FastAPI supports GET, PUT, POST, DELETE, OPTIONS, HEAD, PATCH, and TRACE Rest operations without the need for any additional packages.

FastAPI supports GET, PUT, POST, DELETE, OPTIONS, HEAD, PATCH, and TRACE Rest operations without the need for any additional packages. Native Async Support: FastAPI can handle requests asynchronously using the async / await Python keywords unlike Flask without the need to install any third-party frameworks.

FastAPI can handle requests asynchronously using the / Python keywords unlike Flask without the need to install any third-party frameworks. Dependency Injection: FastAPI comes up with a very powerful and easy to use a built-in injection system to handle dependencies at your endpoint.

FastAPI comes up with a very powerful and easy to use a built-in injection system to handle dependencies at your endpoint. Performance: FastAPI beats every framework when it comes to performance, whereas the most commonly used frameworks, like Flask and Django, lag.

This medium article will help you understand FastAPI in detail.
API Log tracking
By: Deepak Nair
Tags: Java, Logging, Logback, Spring Boot, Rest Api

Image by Robert Balog from Pixabay

I have a set of web services which communicates with each other and I want to build an easy way for tracking logs across these services.

For example I have services A, B and C and consider the communication is from A -> B -> C. I am trying to build a solution for below requirements

Requirements

Track current context for A, B and C using a log id. Track request between two immediate services A -> B and B -> C. Track request across multiple services A -> B -> C using a single log id. No explicit logging for log context ids.

Implementation details

Track current context for A, B and C using a log id.

A unique id will be created and added to log context when service api is called.

Track request between two immediate services A -> B and B -> C.

When a service sends request to other service, the sender will send its contextId in request header “Message-ID”. The receiver service will extract this value from header and add to its log context.

Track request across multiple services A -> B -> C using a single log id.

When a service receives an incoming request, it will check any traceId is present by checking request header “Trace-ID”, if it is not present it will generate one and add to the log context. It will pass this generated or received trace id in all outgoing communication to other services. The other services are also expected to do the same with traceId.

No explicit logging for log context ids.

All log tracking ids contextId, requestId and traceId should come in all application logs without any explicit logging.

To achieve this I have decided to use Mapped Diagnostic Context (MDC) , logback configuration and a servlet filter. All required context ids will be added to MDC by servlet filter.

Servlet filter

Logback configuration

Logging in application class

Sample log in console
ReactJs Step by Step working with Axios - Demo online at http:// jsondev.org
Tags: Parse Json, Jsondev, Restapi, Json Editor Online, Reactjs

Today we learn how to use axios to query json in ReactIs. In this article I provide some basic code samples you have an initial approach to axios.

Install axios:

npm install — save axios

The basic parameters:

url: Path to access the json data you want to be.

headers: headers request For example 'Content-type', 'Authorization', 'Accept' … params: The query parameters on the url.

data: The data you want to put in the query

method: The method of query data. For example POST, GET, PUT …

Getting start with axios:

Step 1: Import library using axios

import axios from 'axios';

Step 2: Declare config

let url = http://jsondev.org/jsondemo let config = {

method: 'GET',

url: this.state.url_test,

headers: headers,

params: params,

data: data

};

Step 3: Create a code using the query axios

axios(config)

.then(function (response) {

console.log('Send REST Api result: ');

let dataResponse = response.data;

if (dataResponse != null) {

console.log(dataResponse);

}

})

.catch(function (error) {

console.log('error request api');

console.log('NetworkStatus: ' + error.toString());



console.log(error.response);

let jsonCallBack = {

data: error.toString(),

status: 0

}

component.props.parentCallback(jsonCallBack);

let statusText ='';

try {

statusText = error.response.statusText;

}catch (e) {



}

console.log(error.toString() + ".

" + statusText);

});

Conclusion:

The above article is just the first step for anyone new to learning about Reactjs and axios. Thank you for reading and sharing.

Demo:

http://jsondev.org

Source codes:

https://github.com/xuanqh/jsoneditoronline.git
React Redux ile Rest API Çağırımı Nasıl Yapılır ?
By: Onur Dayıbaşı
Tags: React, Redux, Front End Development, Axios, Rest Api

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
A Couple of weeks left in GSOD with OpenMRS
By: Saurabh Kumar
Tags: Documentation, Google Season Of Docs, Rest Api, Openmrs

GSoD’s document development phase is close to its completion with only a couple of weeks left before the development phase ends.

In the tenth week, I completed documenting Encounter resource and its subresources and reviewed the already finished sections for mistakes and patches.

This week I also finished the Visit section, which was a blocker for me in previous week but got sorted this week due to help from community members.

I took a lot of help from this thread for documenting a complex resource like Encounter .I added seperate payload for encounter creation since visit information is considered essential (though its not Required).

Work Done so Far

I have made this repository to track all the work done uptill now for RestAPI documentation and I will be updating this every week to include the work done in that week !!

Upcoming Week

I will be trying to finish all the sections of the Order and Form Resource , and simeltanously working on reviewing the docs for any mistakes present in the already finished resources.

happy documenting :)
Rest Api Design
By: Berk Emre Çabuk
Tags: API, Api Design, Rest Api, Dotnet Core

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.
HTTP Status codes and HTTP Methods.
By: Akshay Kashid
Tags: Http Status Code, Nodejs, Http Methods, Rest Api

What are different http status codes?

1xx Informational Response:

101: Switching Protocols

102: Processing

103: Early Hints

2xx Success:

200: OK

201: Created

202: Accepted

203: Non-Authoritative Information

204: No Content

205: Reset Content

206: Partial Content

207: Multi-Status

208: Already Reported

226: IM Used1xx Informational Response

3xx Redirection:

300: Multiple Choices

301: Moved Permanently

302: Found

303: See Other

304: Not Modified

305: Use Proxy

307: Temporary Redirect

308: Permanent Redirect

4xx Client Errors:

400: Bad Request

401: Unauthorized

402: Payment Required

403: Forbidden

404: Not Found

405: Method Not Allowed

406: Not Acceptable

407: Proxy Authentication Required

408: Request Timeout

409: Conflict

410: Gone

411: Length Required

412: Precondition Failed

413: Payload Too Large

414: URI Too Long

415: Unsupported Media Type

416: Range Not Satisfiable

417: Expectation Failed

418: I\m a Teapot

421: Misdirected Request

422: Unprocessable Entity

423: Locked

424: Failed Dependency

425: Unordered Collection

426: Upgrade Required

428: Precondition Required

429: Too Many Requests

431: Request Header Fields Too Large

451: Unavailable For Legal Reasons

5xx Server Errors

500: Internal Server Error

501: Not Implemented

502: Bad Gateway

503: Service Unavailable

504: Gateway Timeout

505: HTTP Version Not Supported

506: Variant Also Negotiates

507: Insufficient Storage

508: Loop Detected

509: Bandwidth Limit Exceeded

510: Not Extended

511: Network Authentication Required

What are different http methods?

There are so many http methods are present. We mostly use following methods for developing REST API Endpoints.

GET: For returning resources

For returning resources POST: For creating new resources

For creating new resources PUT: For updating a resource

For updating a resource PATCH: For modifying a resources

For modifying a resources DELETE: For deleting a resources

There are other different http methods that we are not using but they exists. There are around 34 methods including above methods. Following are the remaining http methods.

ACL

BIND

CHECKOUT

CONNECT

COPY

DELETE

GET

HEAD

LINK

LOCK

M-SEARCH

MERGE

MKACTIVITY

MKCALENDAR

MKCOL

MOVE

NOTIFY

OPTIONS

PATCH

POST

PROPFIND

PROPPATCH

PURGE

PUT

REBIND

REPORT

SEARCH

SOURCE

SUBSCRIBE

TRACE

UNBIND

UNLINK

UNLOCK

UNSUBSCRIBE

How to get information about available http methods and http status codes in node.js project?

Follow below steps to get such information:

Step 1: Create blank node.js project. Create app.js file in which write below code.

const http = require('http') console.log("http methods are ",http.METHODS) console.log("http status Codes are: ", http.STATUS_CODES);

Step 2: Run the code by command node app.js. In your console you will find all the http supported methods and Status codes.

Thank You…!
Difference between SOAP and REST, Use Cases
By: Sasha Andrieiev
Tags: Rest Api, Soap

Having a massive set of possible software solutions is a challenge. Picking the specific approach for specific parts of the web applications is another, and web developers today have to juggle many of these decisions with changing standards or approaches appearing daily.

SOAP was long the standard approach to web service interfaces, although it’s been dominated by REST in recent years. According to Stormpath REST now representing more than 70% of public APIs.

The Similarities

While SOAP and REST share similarities over the HTTP protocol, SOAP is a more rigid set of messaging patterns than REST. The rules in SOAP are important because we can’t achieve any level of standardization without them. REST as an architecture style does not require processing and is naturally more flexible. Both SOAP and REST rely on well-established rules that everyone has agreed to abide by in the interest of exchanging information.

Soap Advantages

SOAP provides the following advantages when compared to REST:

• Language, platform, and transport protocol independent (REST requires the use of HTTP);

• Works well in distributed enterprise environments (REST assumes direct point-to-point communication);

• Standardized;

• Provides significant pre-build extensibility in the form of the WS* standards;

• Built-in error handling;

• Automation when used with certain language products.

REST Advantages

REST is easier to use for the most part and is more flexible. It has the following advantages over SOAP:

• No expensive tools required to interact with the web service;

• Smaller learning curve;

• Efficient (SOAP uses XML for all messages, REST can use smaller message formats);

• Fast (no extensive processing required);

• Closer to other web technologies in design philosophy.

Unless you plan to create your web service, the decision of which protocol to use can be forward to the specialist. Extremely few web services, such as Amazon, support both. Your decision’s focus often centers on which web service best meets your needs, rather than which protocol to use. Follow the guide to learn more.

https://jelvix.com/blog/rest-vs-soap
What is RESTful API?
By: Sahil Agrawal
Tags: Rest, Rest Api, Restful Api, Restful

A RESTful API is an architectural style for designing web applications that uses HTTP requests to access and use data. The RESTful API can also be referred as RESTful web service or REST API.

But wait this got pretty technical right? So before exploring more on what RESTful API is, lets understand what actually is an API.

Application Programming Interface(API) is a set of rules and mechanisms that allow applications to talk to each other. A developer creates an API for the software/service and other applications can use it for the communication. This interface is a software-to-software, not between user-software directly.

Now talking about REST, it is an acronym for REpresentational State Transfer. It is an architectural style which defines a set of rules to be used for communication between web services. REST was presented by Roy Fielding in his PhD dissertation in 2000. It was built on HTTP.
Salesforce GraphQL
By: Aykut Parlak
Tags: Integration, Rest Api, Appitek, GraphQL, Salesforce

Salesforce needs most of the time multiple integrations with other systems (e.g. ERP, Billing, Marketing, etc.), and GraphQL API is a relatively new API approach which makes integrations way easier.

Salesforce Rest API is Good

The Salesforce Rest API is easy to understand and use. Basically, you can set a REST API client (for each programming language a library exists for it, for example for JavaScript it is jsforce), retrieve data or metadata, and then insert/update them back to Salesforce. Getting and setting the data with REST API work fine but the integration requires more than these. Since every system has its own unique data structure and name convention, we need to make multiple data retrieve operations and transform them into the desired structure with a required name convention then interact with other systems data. If we have multiple integrations on multiple services then we need to duplicate these steps for each of them.

GraphQL is Better

Duplicating the work multiple times is not the best practice. In order to reduce the work, we need to make our integrations dynamic. In this content, GraphQL comes into consideration. It is a relatively new concept of API to retrieve and upsert data. For instance, in your integration, if you require to retrieve Accounts with Contacts and Accounts Tasks in a JSON format, then you can either set service on the Salesforce side or make multiple API calls to get the records and transform them in desired name conversion and structure. GraphQL provides this out of the box. For example this GraphQL query:

query {

Customer: Account(Status__c:'Active') {

AccountId: Id

Name

Industry

Status__c

CustomerUser: Contact {

ContactId: Id

Name

}

Task{

Id

Subject

}

}

}

will return the accounts with contacts and tasks in the same structure above as it is requested. You can also set an alias for object and field names.

GraphSQL is Best

To achieve this we need to implement a codebase to parse the requests and responses in the same structure. Appitek has already implemented GraphQL as a native Salesforce package called GraphSQL which is fully free and well documented. Personally, I appreciate the work they have done. It makes things really easier and fun. So please follow the links below to get more details of it.

Give a try in this playground: GraphQL Playground Check the documentation: GraphQL Documentation Install the package in your sandbox and test it: AppExchange Install the package in your Production and enjoy your integrations with it.

A Sample

As the sample request above you can query it either in the playground of GraphSQL or in a REST client of Salesforce.

Playground:

REST Client:
Fundamentals of Rest API response codes
By: Himanshu Gupta
Tags: Rest Api Architecture, Web Services, Http Response, Rest Api, Https

Photo By Markus-Spiske on Unsplash

Introduction

If you are dealing with Restful WebServices that means you are mostly working with HTTP protocols. One of the main aspects of implementing Rest WebServices is to know about the HTTP response codes.

For example, recently I called GET request on Hackerrank football API, and get 302 in the response. The code 302 belongs to the Redirection group that means the original URL is direct to a new URL location ( present in the location header of 302 response ) and I had to call redirected URL for fetching the data.

Original URL: http://jsonmock.hackerrank.com/api/football_matches?year=2010&page=1

Redirected URL: https://jsonmock.hackerrank.com/api/football_matches?year=2010&page=1

The only difference between these two URL is that the First one is working on ‘HTTP’ and the second one is working on the ‘HTTPS’. The extra ‘s’ means its a secure way of transferring the data. HTTPS uses a transport layer and 443 port for communication and the HTTP use ‘80’. This is a very common example where you want to move all your unsafe URL to the secure ones. The load time for HTTP vs HTTPS is available here.

Why should you know about response codes?

1. You can display the appropriate messages to the end-user instead of the error code.

2. Understands the difference between server error codes and client error codes and update the program accordingly.

3. It helps you to write cleaner code.

4. Sometimes the server sends back the generic error code instead of sending back the specific error message. In those scenarios developer, should understands that to which group the error code belongs and proceed accordingly.

5. If you are designing Rest API at the backend server, It’s advisable to prepare and send back the most specific status code.

Most common response codes?

200 ( OK )

204 ( No Content )

302 ( Found )

400 ( Bad Request )

404 ( Not Found )

500 ( Internal Server Error )

503 ( Service is not available )

There are many HTTP response codes which are difficult to remember and the best alternative is to know of about their groups. You can find the HTTP response codes here with descriptions.

Cheers!
Codeigniter Rest Api ve Vuejs Todolist Uygulaması
By: Erkan Keskin
Tags: Codeigniter, Udemy, Rest Api, Vuejs, Eğitim

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
REST API: Representational State Transfer Application Programming Interface
By: Sreehari Nambiar Kt
Tags: API, Request, Rest Api, Definition

What is REST API?

Let's think of real-life situations then an apt example would be, a library. The library has a bookshelf (database), a librarian(the rest API), and the members(client). this is how the library works, when the client makes a request, the rest API identifies it and then figures out what data needs to be gathered and send it to the client.

Types of request — GET — to get a data

- PUT/PATCH — to make changes in an exiting data

- POST — to update a data

- DELETE — to delete a data

Def: — Representational State Transfer(REST) refers to a group of software architecture design constraints that bring about efficient, reliable, and scalable systems.

So REST isn’t a specific technology but rather is a design methodology that produces consistent outputs and predictable behavior by receiving a set of standard methods called VERBS and returning standardized data typically JSON or XML called resource.
Customizing Error Page Handling in Django 3.1
By: Anthony Dattolo
Tags: Custom Views, 404, Mvt, Django, Python

We’ll use an app_name of appName for our purposes, and assume default configurations.

Project settings.py

The simplest way to customize error handling, is to add <errorType>.html files to our APP template root directory. NOT the sub-directory that contains the app-specific templates, but its parent.

By default, and for convenience, Django will automatically look here for certain default method error handling views. They are as follows:

404, page_not_found(): projectName/appName/templates/404.html

500, server_error(): projectName/appName/templates/500.html

403, permission_denied(): projectName/appName/templates/403.html

400, bad_request(): projectName/appName/templates/400.html

*note: unless you change it, your app-specific templates still belong in projectName/appName/templates/appName/

projectName/settings.py

We now need to let Django know we want to look for these default error template overrides, by adding the app level template root directory to the project level settings.py. While we’re here, we also need to set debug mode to false, and set the allowed hosts — we’ll use “*” for now.

#Default base directory

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #App level directory ADD THIS

APPNAME_DIR = os.path.join(BASE_DIR, ‘templates’)

... DEBUG = False ALLOWED_HOSTS = ["*"] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # Add APPNAME_DIR variable to set project template directory for custom # error page handling. eg, 404.html in project template root dir APPNAME_DIR ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]

Custom 404 template

Using the 404 error as an example, let’s edit the 404.html located in our app template root directory. Assume we have a DetailView in our urls.py that allows us to take in a custom string parameter to pass to the detail, and then we use a get_object_or_404() method to access it, and it throws the 404 error because we misspell the URL name.

urlpatterns = [

path(‘appname/<str:customParameterName>/’, AppNameDetailView.as_view(), name=”appname-detail”)

]

The .page_not_found() or default 404 error method, gives us access to a template variable which can be referred to as either request_path or request.path. This will give you the full relative directory path as a string, and so just to demonstrate if you only want to return the misspelled term, we’ll use the builtin template method slice.

<!-- template code: 404.html --> {% extends "appname/layout.html" %} {% block title %} Page Not Found! {% endblock %} {% block body %} <b>{{ request.path|slice:"9:-1" }} does not exist yet!</b> <br> <a href="{% url 'appname:appname-create' %}">Create New Page</a> {% endblock %}

That’s it, if you misspell a URL for a DetailView, it’ll now show the template you defined, and display the misspelled term.
Best Free Cheap Django Hosting in 2021 for Beginners
Tags: Django, Django Hosting, Free Django Hosting, Free Django

Free Django Hosting providers ensure free trial periods, which are equally advantageous for clients and hosts.

Free Django Hosting in 2021: Web Structures are getting complex and Dynamic lately there’s even more need for installing and using frameworks which will build powerful and responsive websites admit that

Django can quickly resolve this problem in minutes think about what you’ll do if you’ll get your hands on a free Django Hosting?

Why Choose Free Django Hosting? Be it the readymade framework Python’s architecture or the stunning

Django community laying hands on a free Django Hosting is useful for any enthusiastic web developer for-fold reasons why should adopt

Django Web Hosting: Framework IncludedDjango’s pride is its robust framework system accompanies plenty of stuff out of

the crate using which you’ll feature develop your web application rather than composing your code you merely got to import the bundles that you simply

got to utilize the power of Python Since Free Django Hosting utilizes PythonBe it paid or free Django hosting Django uses some of the recognition of python to its advantages

python is one among the only — if not the foremost straightforward programing language for amateurs Additionally it’s famous in introductory computing courses around

the world professional and Responsive CommunityDjango’s people group is probably the simplest thing about it they’re useful and effectively handling making the system more

fledgeling and settling the structure while adding new highlights free Django Hosting documentation is extremely intensive and is effective as an independent instructional exercise
Django — custom user authentication
By: Mihai Corciu
Tags: Custom User Model, Django

Initiate a python virtual environment and start a new project:

python -m venv env

source env/bin/activate

pip install Django

pip install django-crispy-forms # for nice forms

mkdir custom_auth

cd custom_auth

django-admin startproject src .

python manage.py startapp accounts

python manage.py runserver

We do not migrate until the configuration of custom user which will be designed by subclassing AbstractUser which subclasses AbstractBaseUser.

Update /src/settings.py

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'crispy_forms',

'accounts',

]

...

AUTH_USER_MODEL = 'accounts.CustomUser'

Update ‘/accounts/models.py’

Update ‘/accounts/forms.py’

Update ‘/src/admin.py’ since Admin is linked to the users definitions.

Run:

python manage.py makemigrations

python manage.py migrate

Create superuser:

python manage.py createsuperuser

Update /src/settings.py adding:

TEMPLATES = [

{

...

'DIRS': [str(BASE_DIR.joinpath('templates'))],

...

},

]

...

LOGIN_REDIRECT_URL = 'home'

LOGOUT_REDIRECT_URL = 'home'

Create directory ‘custom_auth/templates/registration’ and edit ‘/templates/base.html’ (using Bootstrap 4 starter template):

Create ‘/templates/home.html’

‘/templates/registration/login.html’

‘/templates/registration/signup.html’

Update ‘/src/urls.py’

from django.contrib import admin from django.urls import path, include urlpatterns = [

path('admin/', admin.site.urls),

path('', include('accounts.urls')),

path('accounts/', include('django.contrib.auth.urls')),

]

Create ‘/accounts/urls.py’

from django.urls import path from . import views urlpatterns = [

path('', views.home, name = 'home'),

path('accounts/signup/', views.signup, name='signup'),

]

Update ‘/accounts/views.py’

Access ‘localhost:8000’.

The end.

Resources:
Django — Log SQL queries. We all know that Django uses ORM for…
By: Allwin Raju
Tags: Django Logging Queries, Django Orm, Django, Django Log Sql Queries, Django Sql Queries

Photo by Campaign Creators on Unsplash

We all know that Django uses ORM for executing queries instead of direct SQL queries. Behind the scenes, the ORM queries are converted to equivalent SQL queries and then executed. If you have no idea what an ORM is, let me just explain it quickly with an example.

What is an ORM?

The Django web framework includes a default object-relational mapping layer (ORM) that can be used to interact with application data from various relational databases such as SQLite, PostgreSQL, and MySQL.

Example:

Let us say if we want to query all the students from a database. For this purpose with the help of ORM, we would do something like this.

>>> from student.models import Student

>>> Student.objects.all()

<QuerySet [<Student: John>]>

The equivalent SQL syntax for this is (The above Django ORM query will be converted to the following syntax before communicating with the database)

SELECT "student_student"."id", "student_student"."name", "student_student"."school_id" FROM "student_student" LIMIT 21; args=()

I hope now you have an idea about the ORM concept.

Logging SQL queries

Suppose if you would like to log these SQL queries Django provides a way to do that. First, let me show you how to log the queries and then explain why you should log in the latter part of this article.

Simply add the following code to the settings.py file in your Django project.

LOGGING = {

'version': 1,

'disable_existing_loggers': False,

'handlers': {

'file': {

'level': 'DEBUG',

'class': 'logging.FileHandler',

'filename': 'sql.log',

},

},

'loggers': {

'django.db.backends': {

'handlers': ['file'],

'level': 'DEBUG',

'propagate': True,

},

},

}

This code will log your executed SQL queries in a file called ‘sql.log’. Every time you perform any operations on the database, it will be logged here.

This is how my sql.log file looks like:

sql.log

The first value within the braces(0.001) is the execution time for the corresponding SQL statement.

Advantages of logging

Few advantages of logging your SQL queries are,

Find the execution time for each queries. Check if your ORM query is executing exactly the way you want it to be. We can find ways to optimise the ORM queries and statements.

Conclusion

Hope this article is helpful. Follow me for more python and Django articles. Happy coding!